首页 > 解决方案 > 如何使用 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 最简单的方法是什么?

谢谢

标签: pythonpandasdataframesumconditional-statements

解决方案


一种使用pandas.DataFrame.mergewith 的方法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

推荐阅读