Python中基于多分钟窗口的Pandas滚动求和实现问题
Hey there! Looking at your sample DataFrame and the expected Rolling_X values, I’ve got two solid approaches to get you the result you need—one super concise, and another that explicitly leans into the "multi-minute window" logic you mentioned.
方法1:直接用全局累计求和(最快上手)
First off, let’s call it like it is: your Rolling_X is just the running total of the X column from the start of the dataset to each row. Pandas has a built-in function for this that’s perfect:
import pandas as pd # 假设你的DataFrame名为df df['Rolling_X'] = df['X'].cumsum()
If you check the output, it’ll match your expected values exactly:
- The first row’s
X=93gives93 - After adding the first four rows’ X values (93+1+1+2), you get
97 - By the eighth row, the running total hits
99—right on the money.
方法2:基于分钟分组的滚动求和(贴合多分钟窗口需求)
If you want to explicitly tie the calculation to minute-level windows (summing within each minute, then carrying over the total to the next minute), here’s how to do it step by step:
# 步骤1:计算每个分钟分组内的累计和 df['group_cumsum'] = df.groupby('1min')['X'].cumsum() # 步骤2:计算每个分钟分组的总合,再得到这些分组总和的累计值(偏移后排除当前分组) group_totals = df.groupby('1min')['X'].sum().cumsum().shift(fill_value=0) # 步骤3:将之前所有分组的累计总和与当前分组内的累计和相加 df['Rolling_X'] = df['1min'].map(group_totals) + df['group_cumsum'] # 可选:删除临时列 df.drop('group_cumsum', axis=1, inplace=True)
This approach breaks down the problem into minute chunks: first you accumulate values within each minute, then you add the total of all prior minutes to that running sum. The end result is identical to the first method, but it makes the "multi-minute window" logic explicit.
验证结果
Either way, you’ll end up with a Rolling_X column that matches your expected output perfectly, as shown in this snippet:
| dateTime | 1min | hour | minute | X | EXPECTED Rolling_X | Rolling_X |
|---|---|---|---|---|---|---|
| 2017-09-19 02:00:04 | 2017-09-19 02:00:00 | 2 | 0 | 93 | 93 | 93 |
| 2017-09-19 02:00:04 | 2017-09-19 02:00:00 | 2 | 0 | 1 | 94 | 94 |
| 2017-09-19 02:00:04 | 2017-09-19 02:00:00 | 2 | 0 | 1 | 95 | 95 |
| 2017-09-19 02:00:22 | 2017-09-19 02:00:00 | 2 | 0 | 2 | 97 | 97 |
| 2017-09-19 02:01:31 | 2017-09-19 02:01:00 | 2 | 1 | 0 | 97 | 97 |
| 2017-09-19 02:01:31 | 2017-09-19 02:01:00 | 2 | 1 | 1 | 98 | 98 |
| 2017-09-19 02:01:32 | 2017-09-19 02:01:00 | 2 | 1 | 1 | 99 | 99 |
| 2017-09-19 02:01:34 | 2017-09-19 02:01:00 | 2 | 1 | 0 | 99 | 99 |
内容的提问来源于stack exchange,提问作者Giladbi

