pandas 用另一列替换一部分列 [英] pandas replace part of a column with another column
本文介绍了 pandas 用另一列替换一部分列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个pandas数据框,我们称它为data;数据有两列,列a和列b.就像这样:
So i have a pandas data frame, let's call it data;data has two columns,column a and column b.Like this:
a b
0 aaa tts
1 abb tst
2 aba tss
我想用b列替换a列中的每个"a".像这样:
I would like to replace each "a" in column a with column b.Like this:
a b
0 ttsttstts tts
1 tstbb tst
2 tssbtss tss
我绑了这样的东西:
data['a'] = data['a'].apply(lambda x:x.replace("sub-string",data['b']))
但是我除外,没有工作.有人可以告诉我该怎么做.
but as i excepted,did not work.could anyone please tell me what to do.
推荐答案
您需要在df上逐行迭代(传递axis=1
),以便可以访问要替换的各个"b"列值第一栏中所有出现的"a":
You need to iterate row-wise on the df (passing axis=1
) so that you can access the individual 'b' column values that you intend to replace all occurrences of 'a' in the first column:
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
这篇关于 pandas 用另一列替换一部分列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文