Check if dataframe column contains an integer from another dataframe column and add column based on match

Issue

I have two dataframes, a date lookup and a dataframe with the data I’m interested in. I want to look up the row value from dataframe 2 and match with the row from dataframe 1, then add the "date" value for the from dataframe 2 to a new column in dataframe 1.

Dataframe 1

name  sp  val
ccs   2   4.5
ccs   4   5
ccs   5   3
ccs   7   8

lookup dataframe 2

date        sp
2013-10-01  1
2013-11-01  2
2013-12-01  3
2014-01-01  4
2014-02-01  5
2014-03-01  6
2014-04-01  7

final dataframe 1

name  sp  val   date
ccs   2   4.5   2013-11-01
ccs   4   5     2014-01-01
ccs   5   3     2014-02-01
ccs   7   8     2014-05-01

Solution

I didn’t see anything from df2 for sp = 7 so I’m moving forward under the assumption it was left out on accident. However, this should get you the results you requested

df_merge = pd.merge(df1, df2, how = 'inner', on = 'sp')

Answered By – ArchAngelPwn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published