2

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
C_psy
  • 647
  • 8
  • 22

2 Answers2

2

First create a series mapping:

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

Then apply this to each value:

df1 = df1.applymap(s.get)
jpp
  • 159,742
  • 34
  • 281
  • 339
1

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
Mohamed Thasin ah
  • 10,754
  • 11
  • 52
  • 111