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

使用Python Pandas按地点ID分组实现7天窗口滚动计数问题

解决Pandas按地点统计7天窗口事件数的索引问题

我懂你现在的困扰——用groupby加rolling('7D')之后,得到的结果带着多层索引,看起来乱糟糟的,完全不是想要的规整表格对吧?咱们一步步来调整代码,得到你预期的输出。

先看你的原始代码问题

你当前的代码逻辑是对的,但groupby('location_id').rolling()默认会返回**多层索引(分组键location_id + 日期索引)**的结果,所以最终的week_windows是一个带层级索引的Series/DataFrame,不是普通的扁平结构。

# 你的原始代码
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df = df.set_index('date', drop = True)
week_windows = df.groupby('location_id').rolling('7D').count()

解决方案1:重置索引得到扁平结构

直接用reset_index()把多层索引转成普通列,同时保留所有必要的信息:

# 重置索引,把location_id和date变回列
week_windows = df.groupby('location_id').rolling('7D').count().reset_index(drop=False)

这样处理后,week_windows就变成了普通的DataFrame,列包含location_id、date,以及你原数据各列的计数结果。

解决方案2:指定统计列+自定义计数列名(更推荐)

如果你只需要统计某一列的事件数(比如event_id),明确指定列能让结果更清晰,还能给计数列起个直观的名字:

# 假设你要统计的事件列是event_id
week_windows = df.groupby('location_id')['event_id'].rolling('7D').count().reset_index(name='7d_event_count')

这里的name参数会把计数结果的列名设为7d_event_count,一眼就能看出这列的含义。

可选:添加窗口时间范围列

如果需要直观看到每个日期对应的7天窗口是哪段时间,可以额外计算窗口的起始和结束日期:

# 添加上窗口起始(当前日期减6天,凑够7天)和结束日期
week_windows['window_start'] = week_windows['date'] - pd.Timedelta(days=6)
week_windows['window_end'] = week_windows['date']

举个实际例子

假设你的原始数据是这样的:

datelocation_idevent_id
2020-06-011101
2020-06-031102
2020-06-081103
2020-06-022201

用解决方案2的代码后,得到的结果会是:

location_iddate7d_event_countwindow_startwindow_end
12020-06-0112020-05-262020-06-01
12020-06-0322020-05-282020-06-03
12020-06-0812020-06-022020-06-08
22020-06-0212020-05-272020-06-02

小提醒

如果你的数据里有重复的date+location_id组合,count()会统计所有非空行;如果需要统计去重后的事件数量,把count()换成nunique()就可以啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:48:09