user8403237
user8403237

Reputation:

How to map with multiple columns python

I have two data frames as below:

df1:
col1    col2    col3
  1       2       A
  1       2       A
  3       4       B
  3       4       B

df2:
 col1    col2 
  1       2
  3       4

I want to put the value of col3 of df1 in df2 like below:

result:
col1    col2    col3
 1        2       A
 3        4       B

I tried with following code for mapping but getting error message, How to do that

df2['col3'] = df2[['col1','col2]].map(df1.set_index(['col1','col2])['col3'])

Upvotes: 3

Views: 1337

Answers (1)

jezrael
jezrael

Reputation: 863801

Use:

df11 = df1[['col1','col2','col3']].drop_duplicates(['col1','col2'])
df = df2.merge(df11, on=['col1','col2'], how='left')
print (df)
   col1  col2 col3
0     1     2    A
1     3     4    B

Upvotes: 2

Related Questions