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

多列分组多聚合问题:分组后丢失分组列的解决咨询

分组聚合后丢失分组列的解决办法

当前DataFrame

Product NrProduct NameSales RevSales Qty
Product1ProductX11,1
Product2ProductY22,2
Product1ProductX1
Product2ProductY2
Product3ProductZ33,3
Product3ProductZ3

需求与预期结果

我需要按Product Nr和Product Name分组,对Sales Rev和Sales Qty做求和聚合,预期结果如下:

Product NrProduct NameSales RevSales Qty
Product1ProductX11,11
Product2ProductY22,22
Product3ProductZ33,33

遇到的问题

我尝试了以下代码:

df.groupby(['Product Nr', 'Product Name']).agg({'Sales Rev': 'sum', 'Sales Qty':'sum' })

但结果仅返回聚合列,分组列丢失了。另外,Quinten提供的代码返回堆叠的DataFrame且缺少记录:

df.groupby('Product Nr', as_index=False).first()

解决办法

要保留分组列,只需在groupby中添加as_index=False参数,让分组列作为普通列保留,而非转为索引:

df.groupby(['Product Nr', 'Product Name'], as_index=False).agg({'Sales Rev': 'sum', 'Sales Qty':'sum'})

另外注意:你的Sales Rev列是带逗号的字符串格式,直接求和会导致字符串拼接而非数值计算,建议先做数据类型转换:

# 处理空值并转换Sales Rev为数值类型
df['Sales Rev'] = df['Sales Rev'].fillna(0).replace('', 0).str.replace(',', '.').astype(float)
# 处理Sales Qty列
df['Sales Qty'] = df['Sales Qty'].fillna(0).replace('', 0).astype(int)

# 执行分组聚合
result = df.groupby(['Product Nr', 'Product Name'], as_index=False).agg({'Sales Rev': 'sum', 'Sales Qty':'sum'})

# 可选:将Sales Rev转回带逗号的格式
result['Sales Rev'] = result['Sales Rev'].astype(str).str.replace('.', ',')

执行后就能得到你预期的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:50:29