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

如何在同一张pandas dataframe中比较值以标记客户切换行为

实现代码

使用pandas的位移函数shift()即可快速实现你的需求,全部代码仅需数行:

import pandas as pd

# 读取原始数据,csv、excel格式分别对应pd.read_csv、pd.read_excel方法
df = pd.read_csv("你的原始数据文件路径")

# 前置步骤:必须先按客户ID+购买时间升序排序,保证同一客户的记录按时间先后排列
# 请将下方purchase_date替换为你表中实际的时间字段名
df = df.sort_values(by=['customer_id', 'purchase_date'], ascending=True).reset_index(drop=True)

# 判断是否为同一客户
same_customer = df['customer_id'] == df['customer_id'].shift(-1)
# 标记产品类型切换
df['product_type_switch'] = same_customer & (df['product_type'] != df['product_type'].shift(-1))
# 标记购买方式切换
df['purchase_method_switch'] = same_customer & (df['method_of_purchase'] != df['method_of_purchase'].shift(-1))
# 总切换标记:两种切换任意发生一种即算切换
df['has_switch'] = df['product_type_switch'] | df['purchase_method_switch']

# 可选:填充最后一行无下一行对比产生的空值为False
df = df.fillna(False)

筛选切换记录

后续要提取所有发生切换的记录,直接过滤has_switch字段即可:

switch_df = df[df['has_switch'] == True]

如果你的表字段名和示例代码中不一致,替换为实际字段名即可直接运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 17:48:04