使用过滤器和正则表达式,根据 Pandas 数据框中另一个变量的部分文本替换空值
Replace empty values based on part of the text from another variable in Pandas dataframe, using filter and regex expression
我想用我在 Pandas 的另一个变量中找到的部分文本替换空值。为此,我需要使用正则表达式来提取我想要传输的确切文本值,而且还应用了一个过滤器,以便只有那些从开始就没有值的行才会发生变化。
在 SAS 中这很简单,但我在 Python/pandas 中做同样的事情很困难。
下面的例子是我的问题的简化版本。具体来说,我需要将变量 Mount 的任何空值替换为变量 Lens 中前面带有单词“til”(英语中的“for”)的部分文本,在此示例中,第二行,单词“佳能”。如果特定行没有缺少 Mount,则什么也不会发生(如第一行所示)。
在这种作品下,我想出了一个自建的解决方案,但感觉有更有效的方法来做。特别是这个临时变量 Mount_tmp 似乎是不必要的。任何改进我的代码的想法和想法将不胜感激。谢谢
data = {'Lens': ['Canon EF 50mm f/1.8 STM', 'Zeiss Planar T* 85mm f/1.4 til Canon'],
'Mount': ['Canon E', np.nan]}
frame = pd.DataFrame(data)
#Generate temporary variable
frame['Mount_tmp'] = frame['Lens'].str.extract(r'til (\w+\s*\w*)')
#Replace empty data in variable Mount with existing data from Mount_tmp
filt = frame['Mount'].isnull()
frame.loc[filt, 'Mount'] = frame.loc[filt, 'Mount_tmp']
frame.drop('Mount_tmp', axis=1, inplace=True)
尝试:
mask = frame.Mount.isna()
frame.loc[mask, "Mount"] = frame.loc[mask, "Lens"].str.extract(r"til\s+(.*)")[0]
print(frame)
校长:
Lens Mount
0 Canon EF 50mm f/1.8 STM Canon E
1 Zeiss Planar T* 85mm f/1.4 til Canon Canon
我想用我在 Pandas 的另一个变量中找到的部分文本替换空值。为此,我需要使用正则表达式来提取我想要传输的确切文本值,而且还应用了一个过滤器,以便只有那些从开始就没有值的行才会发生变化。
在 SAS 中这很简单,但我在 Python/pandas 中做同样的事情很困难。
下面的例子是我的问题的简化版本。具体来说,我需要将变量 Mount 的任何空值替换为变量 Lens 中前面带有单词“til”(英语中的“for”)的部分文本,在此示例中,第二行,单词“佳能”。如果特定行没有缺少 Mount,则什么也不会发生(如第一行所示)。
在这种作品下,我想出了一个自建的解决方案,但感觉有更有效的方法来做。特别是这个临时变量 Mount_tmp 似乎是不必要的。任何改进我的代码的想法和想法将不胜感激。谢谢
data = {'Lens': ['Canon EF 50mm f/1.8 STM', 'Zeiss Planar T* 85mm f/1.4 til Canon'],
'Mount': ['Canon E', np.nan]}
frame = pd.DataFrame(data)
#Generate temporary variable
frame['Mount_tmp'] = frame['Lens'].str.extract(r'til (\w+\s*\w*)')
#Replace empty data in variable Mount with existing data from Mount_tmp
filt = frame['Mount'].isnull()
frame.loc[filt, 'Mount'] = frame.loc[filt, 'Mount_tmp']
frame.drop('Mount_tmp', axis=1, inplace=True)
尝试:
mask = frame.Mount.isna()
frame.loc[mask, "Mount"] = frame.loc[mask, "Lens"].str.extract(r"til\s+(.*)")[0]
print(frame)
校长:
Lens Mount
0 Canon EF 50mm f/1.8 STM Canon E
1 Zeiss Planar T* 85mm f/1.4 til Canon Canon