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

如何解决Pandas中多层索引行第一层聚合结果不符预期的问题?

解决MultiIndex第一层索引聚合问题

问题场景

现有带多层行索引的DataFrame:

a  fe  gg new_text
(s1, s2)  4   0   3        t
(s1, s3)  3   3   1        t
(s2, s3)  3   2   4        t
(s2, s4)  0   0   4        t
(s3, s1)  2   1   0        t
(s3, s4)  1   1   0        t

需要按第一层索引(s1、s2、s3)聚合,数值列求和,文本列保留原值,预期输出:

a  fe  gg new_text
s1  7   3   4        t
s2  3   2   8        t
s3  3   3   0        t

错误原因分析

使用df.groupby(level=0).agg(['mean'])得到不符合预期的结果,问题出在:

  • 聚合函数选了mean(求平均),但需求是求和
  • 没有针对不同列指定对应聚合逻辑,文本列new_text被自动排除
  • agg(['mean'])会生成多层列结构,且没有合并第一层索引

解决方案

针对不同列指定聚合函数,数值列用sum求和,文本列用first保留第一个值(因所有值都是't',结果一致):

import pandas as pd
import numpy as np
np.random.seed(0)

arr=np.random.randint(5, size=(6, 3))

df = pd.DataFrame(data=arr, index=[('s1','s2'),('s1','s3'),('s2','s3'),('s2','s4'),('s3','s1'),('s3','s4')],
                  columns=['a','fe','gg'])
df['new_text']='t'

# 正确聚合代码
result = df.groupby(level=0).agg({
    'a': 'sum',
    'fe': 'sum',
    'gg': 'sum',
    'new_text': 'first'
})
print(result)

执行后输出与预期一致:

a  fe  gg new_text
s1  7   3   4        t
s2  3   2   8        t
s3  3   3   0        t

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:30:47