0

I need to combine two dataframes where they have similar columns however the 1st dataframe is missing one column i need to add values from 2nd dataframe to 1st

display(df)
id TITLE CODE PRICE
1 John 12 125
2 Katie 14 325
4 Janie 24 550
5 Jacob 32 500
6 John 42 400
display(df2)
id TITLE CODE
7 John 12
8 Katie 14
9 John 42
10 Janie 50
11 Elle 32
12 John 42

Required Output:

id TITLE CODE PRICE
7 John 12 125
8 Katie 14 325
9 John 42 400
10 Janie 50 Nan
11 Elle 32 Nan
12 John 42 400
  • 2
    One way is to use a merge: `df2.merge(df.drop(columns="id"), on=["TITLE", "CODE"], how="left")`. See also https://stackoverflow.com/questions/53645882/pandas-merging-101 – Chrysophylaxs Apr 22 '23 at 11:09

1 Answers1

0

Try:

df2.merge(df[['TITLE', 'CODE', 'PRICE']], on=['CODE', 'TITLE'], how='left')

Output:

   id  TITLE  CODE  PRICE
0   7   John    12  125.0
1   8  Katie    14  325.0
2   9   John    42  400.0
3  10  Janie    50    NaN
4  11   Elle    32    NaN
5  12   John    42  400.0
Scott Boston
  • 147,308
  • 15
  • 139
  • 187