简体   繁体   English

熊猫用另一列替换部分列

[英]pandas replace part of a column with another column

I have a pandas data frame, let's call it data .我有一个 pandas 数据框,我们称之为data data has two columns, column a and column b . data有两列, a列和b列。 Like this:像这样:

  a          b
0 aaa        tts
1 abb        tst
2 aba        tss

I would like to replace each "a" in column a with column b .Like this:我想将 a 列中的每个"a" a b列。像这样:

  a          b
0 ttsttstts tts
1 tstbb      tst
2 tssbtss    tss

I tied something like this :我绑了这样的东西:

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?谁能告诉我该怎么做?

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:您需要在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM