[英]pandas replace part of a column with another column
我有一個 pandas 數據框,我們稱之為data
。 data
有兩列, a
列和b
列。 像這樣:
a b
0 aaa tts
1 abb tst
2 aba tss
我想將 a 列中的每個"a"
a
b
列。像這樣:
a b
0 ttsttstts tts
1 tstbb tst
2 tssbtss tss
我綁了這樣的東西:
data['a'] = data['a'].apply(lambda x:x.replace("sub-string",data['b']))
但正如我例外,沒有工作。 誰能告訴我該怎么做?
您需要在 df 上逐行迭代(通過axis=1
),以便您可以訪問要替換第一列中所有出現的 'a' 的各個 'b' 列值:
In [51]:
df['a'] = df.apply(lambda x: x['a'].replace('a',x['b']), axis=1)
df
Out[51]:
a b
0 ttsttstts tts
1 tstbb tst
2 tssbtss tss
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.