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

问题描述 投票:2回答:2

我试图使用正则表达式替换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警告,它什么都不做。有没有其他方法可以做到这一点?

python pandas
2个回答
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
投票

使用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
© www.soinside.com 2019 - 2024. All rights reserved.