簡體   English   中英

如果它們出現在另一列中,則替換熊貓 df 列中的值

[英]replace values in a pandas df column if they appear in another column

我有一個 pandas 數據to_hide something ,我想替換列中的單詞。 所以我想從這里出發

    to_hide                something
0       bla  there is bla over there
1       sth    i cannot see anything
2  sth else    sth else is beautiful

到這里

  to_hide                    something
0       bla  there is to_hide over there
1       sth        i cannot see anything
2  sth else         to_hide is beautiful

不幸的是,下面會引發錯誤

df = pd.DataFrame({'to_hide':['bla','sth','sth else'], 'something':['there is bla over there','i cannot see anything','sth else is beautiful']})
df.assign(**{'something' : df['something'].str.replace(df['to_hide'], 'to_hide')})
TypeError: 'Series' objects are mutable, thus they cannot be hashed

我該如何編寫它才能正常工作?

您需要在此處使用循環:

df['something'] = [s.replace(pat, 'to_hide')
                   for pat, s in zip(df['to_hide'], df['something'])]

輸出(為清楚起見作為新列):

    to_hide                something                   something2
0       bla  there is bla over there  there is to_hide over there
1       sth    i cannot see anything        i cannot see anything
2  sth else    sth else is beautiful         to_hide is beautiful

另一種方法是使用apply()

df['something'] = df.apply(lambda x: x.something.replace(x.to_hide, 'to_hide'), axis=1)
例子
import pandas as pd

df = pd.DataFrame({'to_hide':['bla','sth','sth else'], 'something':['there is bla over there','i cannot see anything','sth else is beautiful']})
df['something'] = df.apply(lambda x: x.something.replace(x.to_hide, 'to_hide'), axis=1)
輸出
隱藏 某物
0 布拉 那邊有 to_hide
1 某事 我什么都看不到
2 其他 to_hide 很漂亮

暫無
暫無

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

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