简体   繁体   中英

pandas replace part of a column with another column

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

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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