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

如何按zipcode分组统计截止购买日前3个月累计购买量并新增dataframe列

实现方案

前置条件

你已经将Purchase_Date列转换为pandas datetime格式,无需额外处理格式转换。

实现步骤

  • 第一步:先对数据集按Zipcode、Purchase_Date升序排序,保证同邮编下的购买记录按时间顺序排列
import pandas as pd
df = df.sort_values(by=['Zipcode', 'Purchase_Date']).reset_index(drop=True)
  • 第二步:按Zipcode分组后使用时间滚动窗口统计符合要求的购买次数
    这里用pd.DateOffset(months=3)实现精确的3个自然月偏移,closed='left'表示窗口范围为[当前日期-3个月, 当前日期),排除当前记录本身的购买行为,刚好匹配“统计往前推3个月内的购买次数”的需求:
df['Cumulative_purchases'] = (
    df.groupby('Zipcode', group_keys=False)
    .apply(
        lambda group: group.set_index('Purchase_Date')
        .rolling(window=pd.DateOffset(months=3), closed='left')['Id']
        .count()
        .values
    )
)

其他统计逻辑适配

如果你实际需要统计的是所有早于当前日期减3个月的历史购买总次数(即不限制3个月的时间区间,只要购买日期早于截止日都算),可以用如下代码实现:

def count_before_3month(group):
    res = []
    for _, row in group.iterrows():
        cutoff_date = row['Purchase_Date'] - pd.DateOffset(months=3)
        cnt = group[group['Purchase_Date'] <= cutoff_date].shape[0]
        res.append(cnt)
    return res

df['Cumulative_purchases'] = df.groupby('Zipcode', group_keys=False).apply(count_before_3month)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:51:01