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

使用Pandas按客户维度计算两次购买付款之间的间隔时长

Pandas 实现消费断档间隔计算方案

步骤1:数据预处理

先将日期列转换为datetime格式,避免字符串格式影响时间计算:

import pandas as pd

# 原始数据
df = pd.DataFrame({'Customer': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B','B','B','B','B','B', 'B'],
                   'Date': ['1/1/2021', '2/1/2021','3/1/2021', '4/1/2021','5/1/2021', '6/1/2021','7/1/2021','8/1/2021', '1/1/2021', '2/1/2021','3/1/2021', '4/1/2021','5/1/2021', '6/1/2021','7/1/2021', '8/1/2021'], 
                   'Amt': [0, 10, 10, 10, 0, 0, 0, 0, 0, 0, 10, 10, 0, 0, 10, 0]})

# 转换日期格式
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')

步骤2:筛选有效消费记录计算间隔

先过滤掉消费金额为0的无效记录,按客户分组后计算相邻两次消费的断档月数:

# 筛选有效消费记录,按客户、日期升序排序
valid_df = df[df['Amt'] > 0].sort_values(['Customer', 'Date']).copy()

# 按客户分组计算相邻消费的月份差,减1得到中间未消费的断档月数,不受每月天数影响
valid_df['gap_months'] = valid_df.groupby('Customer')['Date'].diff().dt.to_period('M').apply(lambda x: x.n if pd.notna(x) else pd.NA) - 1

# 过滤掉每个用户首次消费的空间隔,按客户聚合得到所有有效断档
result = valid_df[valid_df['gap_months'].notna()].groupby('Customer')['gap_months'].apply(list).reset_index()

输出结果

最终result输出如下,完全匹配需求:

Customergap_months
B[2]

客户A只有连续消费记录,无后续回流消费,因此不会出现在结果中,符合「流失未回流无有效间隔」的规则。如果需要将每个间隔拆为单独行,在聚合后添加.explode('gap_months')即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:45:05