简体   繁体   中英

Pandas Fill values from most recent dates

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)

示例代码的输出

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM