簡體   English   中英

如何使用正則表達式和條件替換熊貓列中的值

[英]How to replace values in a column in pandas using regex and a conditional

我試圖使用正則表達式替換熊貓列(數據框)中的某些值,但是我想基於另一列中的值應用正則表達式。

一個基本的例子;

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警告,它什么也不做。 有替代方法嗎?

為了避免鏈接分配,請分配回去並刪除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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM