Reputation: 3628
I have two dataframes, and I want to add the values from the first dataframe to the second one based on the most recent date that was found. Is there a built in method in pandas to do it?
Sample code:
df1 = pd.DataFrame( {'Time': pd.to_datetime(['1-1-2018', '1-1-2019']), 'Value':[1,2]})
df2 = pd.DataFrame( {'Time': pd.to_datetime(['1-23-2018', '1-22-2019'])} )
df3 = pd.DataFrame( {'Time': pd.to_datetime(['1-23-2018', '1-22-2019']), 'Value':[1,2]} )
display(df1)
display(df2)
print()
print('how to get df3 from df1 and df2?')
display(df3)
Upvotes: 0
Views: 124
Reputation: 31236
merge_asof provides capability you want
df1 = pd.DataFrame( {'Time': pd.to_datetime(['1-1-2018', '1-1-2019']), 'Value':[1,2]})
df2 = pd.DataFrame( {'Time': pd.to_datetime(['1-23-2018', '1-22-2019'])} )
pd.merge_asof(df2, df1, on="Time")
Time | Value | |
---|---|---|
0 | 2018-01-23 00:00:00 | 1 |
1 | 2019-01-22 00:00:00 | 2 |
Upvotes: 1