代码之家  ›  专栏  ›  技术社区  ›  Nordle

如何使用regex和条件

  •  2
  • Nordle  · 技术社区  · 7 年前

    一个基本的例子;

    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 回复  |  直到 7 年前
        1
  •  3
  •   jezrael    7 年前

    为了避免 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
    
        2
  •  1
  •   user3483203    7 年前

    使用 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