-1

I have two data frames here

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'id':[1,2,3,2,5], 'grade':[3,5,3,2,1]})
df2 = pd.DataFrame({'id':[1,2,3], 'final':[6,4,2]})

Now I want to take final column from df2 and add to df1 based on the id column. Here is the desired output

output = pd.DataFrame({'id':[1,2,3,2,5],'grade':[3,5,3,2,1], 'final':[6,4,2,4,np.nan]})

If someone can guide me, that will be awesome.

Thank you so much.

Yun Tae Hwang
  • 925
  • 1
  • 11
  • 25

1 Answers1

0

One way to do it is by using map

df1['final'] = df1['id'].map(df2.set_index('id')['final'])
#result
    id  grade   final
0   1   3       6.0
1   2   5       4.0
2   3   3       2.0
3   2   2       4.0
4   5   1       NaN
Terry
  • 2,541
  • 2
  • 12
  • 24