I have a data frame df1 that looks like the following:
StartDate EndDate
2017-01-10 2017-03-31
2017-04-10 2017-06-30
2017-07-24 2017-09-18
2017-09-30 2017-12-04
and df2 that looks like this:
RecordDate Grade
2017-02-10 93
2017-04-10 88
2017-09-18 89
2018-02-30 96
How can I merge the df2['Grade'] to df1 for the rows that has a df2['RecordDate'] between the duration of df1['StartDate'] and df1['EndDate'] so that it can look like this:
StartDate EndDate RecordDate Grade
2017-01-10 2017-03-31 2017-02-10 93
2017-04-10 2017-06-30 2017-04-10 88
2017-07-24 2017-09-18 2017-09-18 89
2017-09-30 2017-12-04 nan nan
I tried the following code:
# removing time for df1 dates
df1['StartDate'] = pd.to_datetime((pd.to_datetime(df1['StartDate']).dt.date)
df1['EndDate'] = pd.to_datetime((pd.to_datetime(df1['EndDate']).dt.date)
df2['RecordDate'] = pd.to_datetime(df2['RecordDate'])
df1.index = pd.IntervalIndex.from_arrays(df1['StartDate'],df1['EndDate'],closed='both')
df1['Grade'] = df2['RecordDate'].apply(lambda x : df1.iloc[df1index.get_loc(x, tolerance = 3)]['Grade'])
But I receive an error that looks like the following:
TypeError: category, object, and string subtypes are not supported for IntervalIndex