python - 合并具有不同时间戳(不同时间间隔)的两个数据帧
问题描述
我有两个不同的数据框。Df1 具有不同时间间隔的时间戳,如下所示
time sales
2019-01-01 2:00:00 20000
2019-01-01 2:20:00 15600
2019-01-01 2:40:00 15444
...
2019-12-01 3:00:00 13000
2019-12-01 3:30:00 650
Df2 的时间戳为 1 分钟时间间隔,如下所示
time ratings
2019-01-01 2:01:00 0.04
2019-01-01 2:02:00 0.04
2019-01-01 2:03:00 0.04
2019-01-01 2:04:00 0.04
...
2019-12-01 3:00:00 0.01
2019-12-02 3:01:00 0.01
我想合并两个数据框,如下所示
time sales ratings
2019-01-01 2:00:00 20000 [mean of ratings from 2:00:00 ~2:19:00]
2019-01-01 2:20:00 15600 [mean of ratings from 2:20:00 ~2:39:00]
2019-01-01 2:40:00 15444 [mean of ratings from 2:40:00 ~2:59:00]
我将不胜感激任何帮助!谢谢 :)
解决方案
让我们试试pd.cut
:
lower_bounds = pd.cut(df2['time'],
bins=list(df1['time']) + [pd.to_datetime('2050-01-01')],
right=False, include_lowest=True,
labels=df1['time'])
df1['ratings'] = (df2.groupby(lower_bounds)
['rating'].mean()
.reindex(df1['time'])
.values
)
或者您可以使用merge_asof
:
df1['ratings'] = pd.merge_asof(df2, df1.reset_index(),
on='time',
direction='backward'
).groupby('index')['rating'].mean()
推荐阅读
- postgresql - PostgreSQL & BDR:BDR真的是多主控吗,2019年1.x的开源和EOL吗?
- r - 在数据框中的列表元素的第一页上查找单词
- android - 索引 1 处的非法字符 <:>:\:PayPalDataCollector\build\libs\META-INF\MANIFEST.MF
- python-3.x - 指定 Python 3 不干预新行?
- google-data-studio - Google Data Studio:日期范围内第一个值和最后一个值之间的公式差异?
- r - 渲染绘图列表时出现 renderPlot 问题
- javascript - 变量范围冲突Js
- javascript - JS/Regex 匹配方式比它应该的要多
- java - 关闭时重定向到另一个窗口
- vba - VBA SUM 函数用于第 n 行中的多个值