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

如何计算特定用户两步流程从step 1到step 2的日均耗时

计算step1到step2平均耗时的实现方案

核心逻辑

按以下步骤处理可完全匹配需求规则:

  1. 先按user分组、按time升序排序,保证每个用户的行为记录按时间先后排列
  2. 对每个用户的记录,仅保留最近一次step1的时间作为基准:遇到step1就更新基准时间,其他情况沿用最近一次的基准时间
  3. 筛选出同时匹配到基准step1和后续step2的记录,计算两者的时间差
  4. 按日期分组求平均,得到每日平均耗时

代码实现(基于pandas)

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'user': [3249, 2160, 2160, 3249, 5120, 3900, 3900, 3900],
    'action': ['step 1', 'step 1', 'step 2', 'step 2', 'step 1', 'step 1', 'step 1', 'step 2'],
    'time': pd.to_datetime([
        '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'
    ])
})

# 按用户、时间排序
df = df.sort_values(['user', 'time']).reset_index(drop=True)

# 每个用户组内向前填充最近的step1时间
df['latest_step1_time'] = df.groupby('user').apply(
    lambda x: x['time'].where(x['action'] == 'step 1').ffill()
).reset_index(drop=True)

# 筛选出有匹配step1的step2记录
valid_records = df[df['action'] == 'step 2'].dropna(subset=['latest_step1_time']).copy()

# 计算耗时(单位可自行调整,这里用秒)
valid_records['cost_seconds'] = (valid_records['time'] - valid_records['latest_step1_time']).dt.total_seconds()

# 计算每日平均耗时
valid_records['date'] = valid_records['time'].dt.date
daily_avg_cost = valid_records.groupby('date')['cost_seconds'].mean()

print(daily_avg_cost)

示例结果

针对给出的示例数据,最终2021-10-25的平均耗时约为751.67秒,也就是12分32秒左右。如果需要其他时间单位,比如分钟,把total_seconds()除以60即可。

内容的提问来源于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 15:45:05