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

Pandas中合并Time值相同的行并对指定列求和

按Time分组聚合DataFrame的解决方案

步骤说明

  1. 清洗Time列:去除s_前缀,提取纯数字作为分组依据
  2. 转换数值列类型:将tot_1、tot_2从字符串转为整数,保证求和逻辑正常运行
  3. 分组聚合:按Time分组后,Control列保留唯一非空值,tot列执行求和操作

完整代码

import pandas as pd

# 原始数据
df = pd.DataFrame({'Time' : ['s_1234','s_1234', 's_1234', 's_5678', 's_8998','s_8998' ],
                   'Control' : ['A', '', '','B', 'C', ''],
                   'tot_1' : ['1', '1', '1','1', '1', '1'],
                   'tot_2' : ['2', '2', '2','2', '2', '2']})

# 1. 清理Time列前缀
df['Time'] = df['Time'].str.replace('s_', '')

# 2. 转换tot列数据类型
df[['tot_1', 'tot_2']] = df[['tot_1', 'tot_2']].astype(int)

# 3. 分组聚合:Control取非空值,tot列求和
result = df.groupby('Time').agg(
    Control=('Control', lambda x: x[x != ''].iloc[0]),
    tot_1=('tot_1', 'sum'),
    tot_2=('tot_2', 'sum')
).reset_index()

print(result)

输出结果

Time Control  tot_1  tot_2
0  1234       A      3      6
1  5678       B      1      2
2  8998       C      2      4

关键细节说明

  • Time列清洗:通过str.replace去除固定前缀,确保分组键的一致性
  • 数值转换:字符串类型无法直接执行求和运算,必须转为整数或浮点数
  • Control列处理:使用lambda筛选非空值并取第一个,适合同一Time分组下仅存在一个有效Control值的场景;若存在多个不同非空值,可根据需求调整为取众数等逻辑
  • 分组聚合:通过groupby+agg实现多列不同规则的聚合,reset_index将分组键还原为普通列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:35:34