Python 如何使用正则表达式和条件

Python 如何使用正则表达式和条件,python,pandas,Python,Pandas,我试图用regex替换pandas列数据帧中的某些值,但我想基于另一列中的值应用regex 一个基本的例子 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 c

我试图用regex替换pandas列数据帧中的某些值,但我想基于另一列中的值应用regex

一个基本的例子

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
但它似乎不起作用?它不会抛出任何错误或带有复制警告的设置,它只是什么也不做。是否有其他方法可以做到这一点?

对于“避免指定回”和“删除就地”=True:

使用np.where:


谢谢你,杰兹,一如既往。当允许meIs有任何理由使用DataFrame.replace方法@Nordle时,将接受?似乎df['col2']=df.col2[df.col1=='yes'].str.replace'foo?!bar',r'\1'适合你在这里的用途…@JonClements两个Jon有什么区别?但是没有,我使用df没有什么特别的原因。replace@Nordlereplace可以用于用正则表达式一次替换多个列,或者使用映射将一个值转换为另一个值。。。如果您只是在单个列中替换字符串,那么最好像上面那样使用Series.str.replace。。。jezrael可能会就此发表意见,但df.replace在这里是一把敲开螺母的大锤……应该正确地按照df.replace{'col2':'foo?!bar',r'\1',regex=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
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