每日/多日跨国重复客户统计:代码修正与动态优化需求
问题与解决方案
问题描述
需要为数据集创建3个新列:
- Unique customer count:按
Date和Country分组,统计唯一Customer ID的数量; - Repeated from Previous Day:客户当日到访且前一日也到访过,计数加1(单日多次到访仅计1次);
- Repeated from Previous 2 Days:客户当日到访且前两天(前日和前日的前日)都到访过(即连续3天到访),计数加1(单日多次到访仅计1次)。
现有代码存在两个问题:
- 中国地区2023-12-02的
Repeated from Previous 2 Days列计算错误,应为0(因为缺少2023-11-30的数据,无法满足连续3天到访); - 无法支持动态输入连续天数N,即无法灵活统计连续N+1天到访的客户。
预期输出:
| Date | Country | Unique Customer | Repeated from Previous Day | Repeated from Previous 2 Days |
|---|---|---|---|---|
| 2023-12-01 | China | 1 | 0 | 0 |
| 2023-12-01 | South Korea | 1 | 0 | 0 |
| 2023-12-02 | China | 2 | 1 | 0 |
| 2023-12-03 | China | 2 | 2 | 1 |
问题分析
原代码的核心问题:
- 计算
Repeated from Previous 2 Days时,仅判断了当前日期与前一次访问日期的间隔≤2天,未验证是否连续3天都有到访; - 仅对全局最早日期做了特殊处理,忽略了部分日期虽不是全局最早,但缺少更早日期(如2023-12-02的中国,仅存在2023-12-01的数据,无法满足连续3天);
- 未封装逻辑,无法支持动态连续天数的统计需求。
修正与优化后的代码
import pandas as pd def calculate_repeated_visits(df, n_days): """ 计算连续n_days+1天到访的客户数(即当日到访,且之前连续n_days天都到访过) 参数: df: 去重后的数据集(仅保留每个客户每日一条记录) n_days: 需要连续的天数(比如n_days=1对应连续2天,n_days=2对应连续3天) 返回: 分组求和后的结果列 """ # 对每个客户的日期序列,生成前n_days天的日期 shifted_dates = [df.groupby(["Country", "Customer ID"])["Date"].shift(i) for i in range(1, n_days+1)] # 判断连续n_days+1天是否都到访:每个移位后的日期与当前日期的差为i天 conditions = [ (df["Date"] - shifted_date) == pd.Timedelta(days=i) for i, shifted_date in enumerate(shifted_dates, 1) ] # 所有条件需同时满足,且移位后的日期不为空 repeated = pd.Series(True, index=df.index) for cond in conditions: repeated = repeated & cond & cond.notna() # 按日期和国家分组求和 return df.groupby(["Date", "Country"])[repeated].transform("sum").astype(int) # 加载数据 data = { "Date": ["2023-12-01", "2023-12-01", "2023-12-01", "2023-12-02","2023-12-03","2023-12-02","2023-12-03"], "Country": ["China", "China","South Korea","China","China","China","China"], "Customer ID": [1001, 1001, 1002, 1001, 1001,1005,1005] } df = pd.DataFrame(data) # 数据预处理:转换日期格式 + 去重(单日多次访问仅保留1条) df["Date"] = pd.to_datetime(df["Date"]) df_unique = df.drop_duplicates(subset=["Date", "Country", "Customer ID"]).sort_values(["Country", "Customer ID", "Date"]) # 1. 计算Unique customer count df_unique["Unique Customer"] = df_unique.groupby(["Date", "Country"])["Customer ID"].transform("nunique") # 2. 计算Repeated from Previous Day(连续2天到访) df_unique["Repeated from Previous Day"] = calculate_repeated_visits(df_unique, n_days=1) # 3. 计算Repeated from Previous 2 Days(连续3天到访) df_unique["Repeated from Previous 2 Days"] = calculate_repeated_visits(df_unique, n_days=2) # 整理结果并输出 result = df_unique[["Date", "Country", "Unique Customer", "Repeated from Previous Day", "Repeated from Previous 2 Days"]].drop_duplicates().sort_values(["Date", "Country"]).reset_index(drop=True) print(result)
关键优化点说明
- 提前去重:先通过
drop_duplicates保留每个客户每日的唯一记录,避免后续统计重复计数; - 连续到访逻辑修正:通过
shift生成前N天的日期,严格判断每个间隔是否为连续1天,确保只有连续N+1天到访的客户才被统计; - 动态函数封装:
calculate_repeated_visits函数支持输入n_days参数,灵活统计连续n_days+1天到访的客户数(比如n_days=3对应连续4天到访); - 自动处理缺失日期:通过检查
shift后的日期是否非空,自动排除那些缺少更早日期的情况(如中国2023-12-02,因无法找到前2天的记录,自然不会被统计)。
内容的提问来源于stack exchange,提问作者gyiernahfufie
相关产品推荐
相关产品推荐

