python - 如何使用 Pandas 将数据框列部分与 Python 中另一个数据框中包含的时间值相加
问题描述
我有一个看起来像这样的第一个数据帧 df1:
volume
timestamp
2021-01-04 04:00:00 20
2021-01-04 04:30:00 5
2021-01-04 05:00:00 15
2021-01-04 05:30:00 5
2021-01-04 06:00:00 10
2021-01-04 06:30:00 5
2021-01-04 07:00:00 25
2021-01-04 07:30:00 5
2021-01-04 08:00:00 15
2021-01-05 04:00:00 25
2021-01-05 04:30:00 5
2021-01-05 05:00:00 5
2021-01-05 05:30:00 15
2021-01-05 06:00:00 10
2021-01-05 06:30:00 5
2021-01-05 07:00:00 15
2021-01-05 07:30:00 10
2021-01-05 08:00:00 20
... ...
第二个 df2 看起来像这样:
high
timestamp
2021-01-04 05:30:00 134.43
2021-01-05 06:30:00 130.30
... ...
我需要基于 df2 中的时间戳值的 df1 中的卷部分的总和。表示 2021 年 1 月 4 日 04:00:00 到 05:30:00 的成交量总和,以及 2021 年 1 月 5 日 04:00:00 到 06:30:00 的成交量总和,依次为获得这样的结果数据框:
volume_up_to_high
date
2021-01-04 45
2021-01-05 65
... ...
在 Python 中使用 Pandas 最简单的方法是什么?
谢谢
解决方案
一种使用pandas.DataFrame.merge
with 的方法groupby.agg
:
# If not already done so, make `timestamp` columns datetime object
df1["timestamp"] = pd.to_datetime(df1["timestamp"])
df2["timestamp"] = pd.to_datetime(df2["timestamp"])
# Make `date` columns each as a common point for merge
df1["date"] = df1["timestamp"].dt.date
df2["date"] = df2["timestamp"].dt.date
# merge then groupby
df = df1.merge(df2, on="date")
new_df = df[df["timestamp_x"].le(df["timestamp_y"])].groupby("date").agg(volume_up_to_high=("volume", sum))
print(new_df)
输出:
volume_up_to_high
date
2021-01-04 45
2021-01-05 65
推荐阅读
- r - 月-年组合的 stat_count
- node.js - 如何签署请求对象并发送请求?
- r - 在 R 中使用 data.table::fread 以非 ISO 格式读取日期列
- excel - 检索网站表以导入 Excel
- google-bigquery - BigQuery如何订购嵌套和重复的列?
- reactjs - React-bootstrap Navbar 示例似乎没有在本地呈现
- asp.net-mvc - Identity Server 4:从外部提供者注销
- c++ - 分解数字时输出中的额外“0”
- docker - 如何使用 3 个不同的容器在 docker 上集群 rethinkdb 数据库?
- javascript - 如何在 7 天前获得凌晨 12 点?