0

I have two data frames df1 and df2

df1

id     name
ada1  mike
ad23  tom
cev2  tim

df2

 id   month.   sales
 ada1. 1/11.    23
 ada1. 4/11.    34
 ad23. 3/12.    34
 cev2. 4/11.    32

I need :

 id   month.   sales name
 ada1. 1/11.    23.  mike
 ada1. 4/11.    34.  mike
 ad23. 3/12.    34.  tom
 cev2. 4/11.    32.  tim

I am struck between left join or right join, what should i use.

3 Answers3

0

Use pd.merge:

>>> df2.merge(df1, on='id', how='left')

     id month  sales  name
0  ada1  1/11     23  mike
1  ada1  4/11     34  mike
2  ad23  3/12     34   tom
3  cev2  4/11     32   tim
Corralien
  • 70,617
  • 7
  • 16
  • 36
0

Use map, since you are joining\merging on one column and returning one column.

df2['name'] = df2['id'].map(df1.set_index('id')['name'])

Map will outperform join\merge.

Scott Boston
  • 133,446
  • 13
  • 126
  • 161
0

Providing two methods that can help based on problem set

import pandas as pd

# retain df2 and merge df1 use 'leftjoin'
df2.merge(df1, on='id', how='left')

# Full Join, also known as Full Outer Join, returns all those records which 
 either have a match in the left or right dataframe

pd.merge(df2,df1,on='id',how='outer',indicator=True)
AKS
  • 57
  • 3