You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中基于多分钟窗口的Pandas滚动求和实现问题

实现基于多分钟窗口的滚动求和(匹配预期Rolling_X)

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=93 gives 93
  • 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:

dateTime1minhourminuteXEXPECTED Rolling_XRolling_X
2017-09-19 02:00:042017-09-19 02:00:0020939393
2017-09-19 02:00:042017-09-19 02:00:002019494
2017-09-19 02:00:042017-09-19 02:00:002019595
2017-09-19 02:00:222017-09-19 02:00:002029797
2017-09-19 02:01:312017-09-19 02:01:002109797
2017-09-19 02:01:312017-09-19 02:01:002119898
2017-09-19 02:01:322017-09-19 02:01:002119999
2017-09-19 02:01:342017-09-19 02:01:002109999

内容的提问来源于stack exchange,提问作者Giladbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:51:27