python - 如何从另一个 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
非常感谢任何帮助!
解决方案
使用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
推荐阅读
- python - Python 3 Tkinter | 更改文本小部件中“:”之间的单词的颜色/样式
- css - 我需要在 django 中指定一些 id 以便稍后在引导程序中添加它
- bash - 使用 popd、pushd 时获取我的目录堆栈中不同目录路径的引用
- jenkins - 使用多项目 gradle 构建创建 Jenkins 管道
- java - Spring Security 的身份验证问题,资源 API 上的 JWT
- web-crawler - Does Stormcrawler follow secondary JavaScript page content loads?
- javascript - 通过两点的“无限”线
- sql-server - 已还原数据库的 SQL Server 2012 登录问题
- javascript - 将对象方法传递给字符串数组(Javascript)
- xml - 在循环内插入数组