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

使用Pandas计算状态变化数据中类别按时间戳的时间占比

问题描述

我们有一个记录对象状态随时间变化的DataFrame,每条记录对应一个状态和时间戳,数据如下:

id  category timestamp
0   A        2022-10-04T00:00:00.000Z   
1   B        2022-10-04T02:00:00.000Z
2   C        2022-10-04T10:00:00.000Z
3   A        2022-10-04T11:00:00.000Z
4   B        2022-10-04T12:00:00.000Z

需要计算id为0-3的各category对应的持续时间及总时间占比,最终得到如下结果:

A: 3h / 0.2500
B: 8h / 0.6667
C: 1h / 0.0833
解决方案

1. 数据预处理

导入pandas,构造示例数据并将timestamp列转为UTC时区的datetime格式,方便后续时间计算:

import pandas as pd

# 构造数据
data = {
    'id': [0, 1, 2, 3, 4],
    'category': ['A', 'B', 'C', 'A', 'B'],
    'timestamp': ['2022-10-04T00:00:00.000Z', '2022-10-04T02:00:00.000Z',
                  '2022-10-04T10:00:00.000Z', '2022-10-04T11:00:00.000Z',
                  '2022-10-04T12:00:00.000Z']
}
df = pd.DataFrame(data)

# 转换时间戳格式
df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True)

2. 计算各状态持续时长

筛选出id为0-3的行,给每行添加下一个状态的时间戳,通过时间差计算当前状态的持续时长(转为小时单位):

# 筛选目标数据
target_df = df[df['id'].between(0, 3)].copy()

# 获取下一个状态的时间戳
target_df['next_timestamp'] = target_df['timestamp'].shift(-1)

# 计算持续时长(小时)
target_df['duration_h'] = (target_df['next_timestamp'] - target_df['timestamp']).dt.total_seconds() / 3600

3. 汇总时长与计算占比

按category分组求和得到每个分类的总时长,再计算各分类时长占总时长的比例(保留4位小数):

# 按分类汇总总时长
duration_summary = target_df.groupby('category')['duration_h'].sum().reset_index()

# 计算总时长
total_h = duration_summary['duration_h'].sum()

# 计算占比并保留4位小数
duration_summary['proportion'] = (duration_summary['duration_h'] / total_h).round(4)

4. 格式化输出结果

按要求的格式打印最终结果:

for _, row in duration_summary.iterrows():
    print(f"{row['category']}: {int(row['duration_h'])}h / {row['proportion']}")

运行后输出:

A: 3h / 0.2500
B: 8h / 0.6667
C: 1h / 0.0833

内容的提问来源于stack exchange,提问作者Andre S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:50:25