-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]})

What approach can I try?

halfer
  • 19,824
  • 17
  • 99
  • 186
Yun Tae Hwang
  • 1,249
  • 3
  • 18
  • 30

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,761
  • 2
  • 14
  • 28