C_psy
C_psy

Reputation: 647

Search and replace matching values across data frames in Python

I have the following Pandas Dataframes:

df1:

C   D   E   F   G
111 222 333 444 555
666 777

df2:

A    B 
111  3
222  4
333  3
444  3
555  4
100  3
666  4
200  3
777  3

I need to look up in df2 to find matching value from df1.A Then replace that value in df1 with the paired valued in df2.B

So the required output would be:

C   D   E   F   G
3   4   3   3   4
4   3

I tried a left merge and thought to try and reshape the values across but thought there must be a simpler / cleaner direct search and replace method. Any help much appreciated.

Upvotes: 2

Views: 53

Answers (2)

Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

try this,

temp=df2.set_index('A')['B']
print df1.replace(temp)

Output:

   C  D    E    F    G
0  3  4  3.0  3.0  4.0
1  4  3  NaN  NaN  NaN

Upvotes: 1

jpp
jpp

Reputation: 164683

First create a series mapping:

s = df2.set_index('A')['B']

Then apply this to each value:

df1 = df1.applymap(s.get)

Upvotes: 2

Related Questions