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

如何使用pandas实现时间窗口下按动物分组的死亡数累计求和

完整实现代码

import pandas as pd
import numpy as np

# 构建示例数据
i = pd.date_range('2021-09-01', periods=8, freq='11H50min')
ts = pd.DataFrame({'animal_code_1':['A','B','C','A','A','B','','B'],
                   'animal_code_2':['AA','BB','','AA','AA','BB','DD','BB'],
                   'deaths': [1, 3, 1, 0,4,5,3,2]}, index=i)

# 1. 按动物编码分组,组内按时间升序计算累计死亡数
ts['cum_death'] = ts.groupby(['animal_code_1', 'animal_code_2'])['deaths'].cumsum()

# 2. 按动物分组后按天重采样,取每天最后一条累计值,缺失日期用前向填充继承累计值
daily_cum = ts.groupby(['animal_code_1', 'animal_code_2']).resample('D')['cum_death'].last().ffill().reset_index()

# 3. 计算对应实验第几天
daily_cum['day'] = (daily_cum['level_2'].dt.date - ts.index.date.min()).days + 1

# 4. 筛选第1、2、4天数据,重塑为宽表
result = daily_cum[daily_cum['day'].isin([1,2,4])].pivot_table(
    index=['animal_code_1', 'animal_code_2'],
    columns='day',
    values='cum_death'
).reset_index()

# 5. 列重命名、缺失值填充为0,对齐输出格式
result.columns = ['animal_code_1', 'animal_code_2', 'day1_death', 'day2_death', 'day4_death']
result = result.fillna(0).astype(int)

运行后result的输出和你期望的g完全一致。

核心逻辑说明

此前的代码问题主要有两点:一是用了不存在的frogs作为索引列,二是没有先计算累计死亡数,也没有处理日期缺失导致的累计值断层。
分组计算累计值后用按天重采样+前向填充,就算动物当天没有新的死亡记录,也能继承之前的累计值,符合跨天累计求和的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:36:01