使用过滤器和正则表达式根据 Pandas 数据框中另一个变量的部分文本替换空值

问题描述

我想用我在 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