如何使用正则表达式和条件替换熊猫列中的值

时间:2018-08-30 07:03:08

标签: python pandas

我正在尝试使用正则表达式替换熊猫列(数据框)中的某些值,但我想基于另一列中的值应用正则表达式。

一个基本示例;

index  col1  col2
1      yes   foobar
2      yes   foo
3      no    foobar

使用以下内容;

df.loc[df['col1'] == 'yes', 'col2'].replace({r'(fo)o(?!bar)' :r'\1'}, inplace=True, regex=True)

我期望得到以下结果;

index  col1  col2
1      yes   foobar
2      yes   fo
3      no    foobar

但是它似乎不起作用?它不会引发任何错误或settingwithcopy警告,它什么也不做。有其他替代方法吗?

2 个答案:

答案 0 :(得分:3)

为避免chained assignments分配回去并删除inplace=True

mask = df['col1'] == 'yes'
df.loc[mask, 'col2'] = df.loc[mask, 'col2'].replace({r'(fo)o(?!bar)' :r'\1'}, regex=True)

print (df)
  col1    col2
1  yes  foobar
2  yes      fo
3   no  foobar

答案 1 :(得分:1)

使用np.where

df.assign(
    col2=np.where(df.col1.eq('yes'), df.col2.str.replace(r'(fo)o(?!bar)', r'\1'), df.col2)
)

  col1    col2
1  yes  foobar
2  yes      fo
3   no  foobar