首页 > 解决方案 > 如何从另一个 DataFrame 添加数据,其中不同的日期粒度匹配?

问题描述

你好,我对 python 和 pandas 很陌生

我有两个 DataFrame,一个在较高的时间范围内,具有每日粒度,一个在较低的时间范围内,具有每小时粒度。我想要做的是将“趋势”数据从较高的时间范围附加到日期相同的较低时间范围内。我遇到了一些麻烦。我的 DataFrames 有日期时间索引,看起来像这样:

更高的时间范围:

 time                  state
2015-06-03 22:00:00    bullish
2015-06-04 22:00:00    bullish
2015-06-05 22:00:00    bearish
2015-06-06 22:00:00    bullish
2015-06-07 22:00:00    bullish
2015-06-08 22:00:00    bullish

较低的时间范围:

time                   state
2015-06-05 05:00:00    bullish
2015-06-05 09:00:00    bullish
2015-06-05 13:00:00    bullish
2015-06-05 17:00:00    bullish
2015-06-07 21:00:00    bullish
2015-06-08 01:00:00    bullish

我想要的结果是这样的:

time                   state     trend
2015-06-05 05:00:00    bullish   bearish
2015-06-05 09:00:00    bullish   bearish
2015-06-05 13:00:00    bullish   bearish
2015-06-05 17:00:00    bullish   bearish
2015-06-07 21:00:00    bullish   bullish
2015-06-08 01:00:00    bullish   bullish

非常感谢任何帮助!

标签: pythonpandasdatedataframe

解决方案


使用merge_asof

d = {'state_x':'state','state_y':'trend'}
df = pd.merge_asof(df2, df1, on='time', direction='forward').rename(columns=d)

print (df)
                 time    state    trend
0 2015-06-05 05:00:00  bullish  bearish
1 2015-06-05 09:00:00  bullish  bearish
2 2015-06-05 13:00:00  bullish  bearish
3 2015-06-05 17:00:00  bullish  bearish
4 2015-06-07 21:00:00  bullish  bullish
5 2015-06-08 01:00:00  bullish  bullish

推荐阅读