8

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?

1 Answer 1

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much this problem has bugged me for a long time and now my mind is finally at peace~~~
Sorry, i get an error: TypeError: replace() argument 2 must be str, not float

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.