0

I have df1 as follow:

Name    |  ID
________|_____
Banana  |  10
Orange  |  21
Peach   |  115

Then I have a df2 like this:

ID   Price
10    2.34
10    2.34
115   6.00

I want to modify df2 to add another column name Fruit to get this as output:

 ID   Fruit     Price
 10   Banana    2.34
 10   Banana    2.34
 115  Peach     6.00
 200  NA        NA

I can use iloc to get one specific match but how to do it in all records in the df2?

merchmallow
  • 774
  • 3
  • 15

1 Answers1

0

Have you tried looking at the merge function ?

pd.merge(df1, df2)

Output :

    Name    Id  Price
0   Banana  10  2.34
1   Banana  10  2.34
2   Peach   115 6.00

EDIT : If you want to add only a specific column from df2 :

df = pd.merge(df1,df2[['Id','Price']],on='Id', how='left')

Output :

Name    Id  Price
0   Banana  10  2.34
1   Banana  10  2.34
2   Orange  21  NaN
3   Peach   115 6.00
Jules Civel
  • 449
  • 2
  • 13
  • I'll try. df1 has 33 columns and df2 has 17. I just want to add one more column in df2. Merge will do this, right? – merchmallow Jul 07 '21 at 09:04
  • If you only want to merge 1 column from df2 into df1, you should take a look at [this](https://stackoverflow.com/questions/17978133/python-pandas-merge-only-certain-columns) question. I'll edit my answer. – Jules Civel Jul 07 '21 at 09:11