多列分组多聚合问题:分组后丢失分组列的解决咨询
分组聚合后丢失分组列的解决办法
当前DataFrame
| Product Nr | Product Name | Sales Rev | Sales Qty |
|---|---|---|---|
| Product1 | ProductX | 11,1 | |
| Product2 | ProductY | 22,2 | |
| Product1 | ProductX | 1 | |
| Product2 | ProductY | 2 | |
| Product3 | ProductZ | 33,3 | |
| Product3 | ProductZ | 3 |
需求与预期结果
我需要按Product Nr和Product Name分组,对Sales Rev和Sales Qty做求和聚合,预期结果如下:
| Product Nr | Product Name | Sales Rev | Sales Qty |
|---|---|---|---|
| Product1 | ProductX | 11,1 | 1 |
| Product2 | ProductY | 22,2 | 2 |
| Product3 | ProductZ | 33,3 | 3 |
遇到的问题
我尝试了以下代码:
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
相关产品推荐
相关产品推荐

