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

Pandas计算同客户上次到访离场与本次到访入场时间的天数差

实现方案

你已经完成了按客户ID分组对到访入场时间排序的步骤,后续可直接通过groupby+shift偏移字段获取同客户上一次的离场时间,再做差值计算即可,完整实现代码如下:

import pandas as pd

# 可选:如果还未对数据集按客户+入场时间排序,先执行排序
temp = temp.sort_values(by=['customer ID', 'in time'], ascending=True).reset_index(drop=True)

# 第一步:先确保时间字段为datetime类型,避免计算报错
temp['in time'] = pd.to_datetime(temp['in time'])
temp['out time'] = pd.to_datetime(temp['out time'])

# 第二步:按customer ID分组,将out time向下偏移1行,得到同客户上一次到访的离场时间
temp['prev_out_time'] = temp.groupby('customer ID')['out time'].shift(1)

# 第三步:计算时间差,提取天数单位
temp['time difference (days)'] = (temp['in time'] - temp['prev_out_time']).dt.days

# 可选:如果首次到访的空差值需要填充为0,可加下面这行
temp['time difference (days)'] = temp['time difference (days)'].fillna(0)

逻辑说明

  • shift(1)的作用是将分组后的单列数据整体向下移动1行,原本第n行的out time会移动到第n+1行,刚好对应同客户第n+1次到访的上一次离场时间
  • 计算得到的时间差默认单位为天,首次到访因为没有上一次离场记录,会默认返回NaN,可根据业务需求选择是否填充
  • 你之前计算的RANK列仅可用于验证排序结果,不需要作为计算的必要字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:45:02