使用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']
举个实际例子
假设你的原始数据是这样的:
| date | location_id | event_id |
|---|---|---|
| 2020-06-01 | 1 | 101 |
| 2020-06-03 | 1 | 102 |
| 2020-06-08 | 1 | 103 |
| 2020-06-02 | 2 | 201 |
用解决方案2的代码后,得到的结果会是:
| location_id | date | 7d_event_count | window_start | window_end |
|---|---|---|---|---|
| 1 | 2020-06-01 | 1 | 2020-05-26 | 2020-06-01 |
| 1 | 2020-06-03 | 2 | 2020-05-28 | 2020-06-03 |
| 1 | 2020-06-08 | 1 | 2020-06-02 | 2020-06-08 |
| 2 | 2020-06-02 | 1 | 2020-05-27 | 2020-06-02 |
小提醒
如果你的数据里有重复的date+location_id组合,count()会统计所有非空行;如果需要统计去重后的事件数量,把count()换成nunique()就可以啦。
内容的提问来源于stack exchange,提问作者Grygger
相关产品推荐
相关产品推荐

