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

使用Pandas计算两步操作流程的用户日均转化时长(支持跨天场景)

问题根源

原代码的核心错误有两点:

  1. 透视表把日期加入了索引,导致跨天用户的step 1和step 2被拆分到不同行,无法正确配对计算差值
  2. 统计分组依据错误,没有按照要求将耗时计入step 2完成的日期

正确实现代码

import pandas as pd

# 原始数据处理
data = {'user': [3249, 2160, 2160, 3249, 5120, 3900, 3900, 3900, 5200, 5200], 
        'action': ['step 1', 'step 1', 'step 2', 'step 2', 'step 1', 'step 1', 'step 1', 'step 2', 'step 1', 'step 2'], 
        'time': ['2021-10-25 19:45:43', '2021-10-25 19:48:46', '2021-10-25 19:50:21', '2021-10-25 19:57:34', '2021-10-25 20:30:56', '2021-10-25 20:35:40', '2021-10-25 20:50:59', '2021-10-25 21:15:08', '2021-10-25 18:23:41', '2021-10-26 18:49:38']}
df = pd.DataFrame(data)
df['time'] = pd.to_datetime(df['time'])
df.sort_values('time', inplace=True)

# 1. 按用户分组,提取每个用户各步骤的最后操作时间(自动过滤重复操作)
user_step = df.groupby(['user', 'action'])['time'].last().unstack().reset_index()
# 过滤掉未完成两步操作的用户
user_step = user_step.dropna(subset=['step 1', 'step 2'])

# 2. 计算耗时,提取step2完成日期作为分组依据
user_step['duration'] = (user_step['step 2'] - user_step['step 1']).dt.total_seconds()
user_step['date'] = user_step['step 2'].dt.date

# 3. 按日期分组求平均,格式化输出
result = user_step.groupby('date')['duration'].mean().round().reset_index()
result.columns = ['Date', 'Avg Duration']
result['Avg Duration'] = result['Avg Duration'].astype(int).astype(str) + ' seconds'

输出结果

DateAvg Duration
2021-10-25752 seconds
2021-10-2687957 seconds

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:48:02