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

基于时间差对日期时间列分组实现TV观看会话划分

遥控器点击会话聚合解决方案

原始数据

Name        Time
John        2022-12-06 02:37:25
John        2022-12-06 10:37:25
John        2022-12-06 10:42:34            
John        2022-12-06 10:47:12
John        2022-12-06 10:52:10

规则说明

  • 两次点击间隔≤10分钟:归为同一连续观看会话,时间聚合为一个列表
  • 间隔>10分钟:判定为独立会话,单独生成一个列表

实现代码(Python)

import pandas as pd

# 构造原始数据
data = pd.DataFrame({
    'Name': ['John']*5,
    'Time': ['2022-12-06 02:37:25', '2022-12-06 10:37:25',
             '2022-12-06 10:42:34', '2022-12-06 10:47:12',
             '2022-12-06 10:52:10']
})

# 转换时间格式并排序
data['Time'] = pd.to_datetime(data['Time'])
data = data.sort_values('Time').reset_index(drop=True)

# 计算相邻时间间隔(分钟)
data['time_diff'] = data['Time'].diff().dt.total_seconds() / 60

# 标记会话分组:间隔超10分钟则新建会话
data['session_id'] = (data['time_diff'] > 10).cumsum()

# 聚合每个会话的时间列表
result = data.groupby(['Name', 'session_id'])['Time'].apply(
    lambda x: x.dt.strftime('%Y-%m-%d %H:%M:%S').tolist()
).reset_index()

# 整理输出格式
result = result[['Name', 'Time']].rename(columns={'Time': 'Aggregated_timelist'})

# 打印结果
print(result.to_string(index=False))

输出结果

Name     Aggregated_timelist
John     ['2022-12-06 02:37:25']
John     ['2022-12-06 10:37:25', '2022-12-06 10:42:34', '2022-12-06 10:47:12', '2022-12-06 10:52:10']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:45:30