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

如何按Animal分组并使用8小时间隔的pd.Grouper汇总dosis?

按动物分组并按8小时时间间隔汇总给药剂量

原始数据

AnimalStarttimedosis
Tiger2019-02-18 10:06:0020
Tiger2019-02-19 10:06:002
Fish2018-02-18 10:06:002
Ape2021-04-10 10:06:0012
Ape2021-04-10 12:06:002

目标结果

AnimalStarttimedosis
Tiger2019-02-18 16:00:0020
Tiger2019-02-19 16:00:002
Fish2018-02-18 16:00:002
Ape2021-04-10 16:00:0014

需求说明

按Animal分组,将同一动物在8小时时间间隔内的dosis求和,时间间隔以freq='8h'为准,最终保留间隔的结束时间(如示例中的16:00)。

错误写法分析

你之前尝试的两种写法问题在于:

  • df.groupby(pd.Grouper(key=('Animal','Starttime'), freq='8h')).sum():pd.Grouper的key参数不支持传入元组,无法同时按类别和时间分组
  • df.groupby('Animal').apply(pd.Grouper(key='Starttime', freq='8h')).sum():apply直接传入pd.Grouper无法正确执行分组逻辑,需要在apply内部完成分组求和操作

正确实现代码

import pandas as pd

# 确保Starttime为datetime类型(若原始数据不是则执行此步)
df['Starttime'] = pd.to_datetime(df['Starttime'])

# 复合分组:按Animal + 8小时时间间隔,求和dosis
result = df.groupby(
    ['Animal', pd.Grouper(key='Starttime', freq='8h', label='right')]
)['dosis'].sum().reset_index()

print(result)

代码说明

  1. 时间类型转换:先将Starttime列转为datetime类型,保证时间分组逻辑有效
  2. 复合分组设置:同时用Animal列和pd.Grouper分组,label='right'指定使用时间间隔的结束时间作为分组标签(对应示例中10:06所在区间的结束时间16:00)
  3. 格式化结果:对dosis求和后,用reset_index()将分组索引转为普通列,得到目标格式的DataFrame

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:48:16