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

如何在含非一致秒级时间的Pandas DataFrame中按ID计算每日均价?

Pandas按selection_id分组计算每日均价的高效方案

直接使用Pandas的groupby同时按**日期(从datetime索引提取)**和selection_id字段分组,再对price列求均值即可,无需拆分多个DataFrame,是最高效的实现方式。

原始数据

索引(datetime)selection_idprice
2023-05-13 05:57:07.55411.50
2023-05-13 06:08:59.19311.56
2023-05-13 06:08:59.08511.61
2023-05-13 06:08:59.08511.50
2023-05-13 06:08:59.08511.51
2023-05-13 06:08:59.085453.12
2023-05-13 05:57:07.554453.16
2023-05-13 06:08:59.193453.12
2023-05-13 06:08:59.085453.16
2023-05-13 06:08:59.085453.12
2023-05-13 06:08:59.085987.05
2023-05-13 06:08:59.085987.52
2023-05-13 05:57:07.554987.11
2023-05-13 06:08:59.193987.99
2023-05-13 06:08:59.085987.50
2023-05-13 06:08:59.085987.20
2023-05-13 06:08:59.085987.65
2023-05-13 06:08:59.085987.45
2023-05-14 05:57:07.55412.50
2023-05-14 06:08:59.19312.56
2023-05-14 06:08:59.08512.61
2023-05-14 06:08:59.08512.50
2023-05-14 06:08:59.08512.51
2023-05-14 06:08:59.085452.12
2023-05-14 05:57:07.554452.16
2023-05-14 06:08:59.193452.12
2023-05-14 06:08:59.085452.16
2023-05-14 06:08:59.085452.12
2023-05-14 06:08:59.085987.05
2023-05-14 06:08:59.085987.52
2023-05-14 05:57:07.554987.11
2023-05-14 06:08:59.193987.99
2023-05-14 06:08:59.085987.50
2023-05-14 06:08:59.085987.20
2023-05-14 06:08:59.085987.65
2023-05-14 06:08:59.085987.45

实现步骤

1. 确认索引类型(可选)

如果DataFrame索引还不是datetime类型,先转换:

import pandas as pd
df.index = pd.to_datetime(df.index)

2. 执行分组聚合

核心代码:

# 按索引日期 + selection_id 分组,计算price均值
daily_avg = df.groupby([df.index.date, 'selection_id'])['price'].mean().reset_index()

# 重命名列名匹配期望格式
daily_avg.columns = ['date', 'selection_id', 'price']

# 可选:将date列设为索引
daily_avg = daily_avg.set_index('date')

最终结果

日期selection_idprice
2023-05-1311.536
2023-05-13453.136
2023-05-13987.434
2023-05-1412.536
2023-05-14452.136
2023-05-14987.434

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:27:20