Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have two DataFrames.

df1:

A | B | C

-----|---------|---------|

25zx | b(50gh) | |

50tr | a(70lc) | c(50gh) |

df2:

  A | B

-----|-----

25zx | T

50gh | K

50tr | K

70lc | T

I want to replace the values in df1. The row that I am comparing is df2['A'], but the value which I want to put into the df1 is a value from row df['B']. Note my goal is for the new value to replace the whole cell.

So my final table would look like:

df3:

A | B | C

-----|---------|---------|

  T | K | |

  K | T | K |

1 Answer

0 votes
by (36.8k points)

You can use the DataFrame.replace with the optional parameter regex=True to replace values in df1 from a replacement series s:

s = pd.Series(df2['B'].values, index=r'.*?'+ df2['A'] + r'.*')

df3 = df1.replace(s, regex=True)

   A  B     C

0  T  K  None

1  K  T     K

Improve your knowledge in data science from scratch using data scientist

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...