python - Pandas groupby : can I select an agg function by one level of a column MultiIndex?

标签 python pandas pandas-groupby

我有一个带有多列索引的 pandas DataFrame:

columns=pd.MultiIndex.from_tuples(
    [(c, i) for c in ['a', 'b'] for i in range(3)])
df = pd.DataFrame(np.random.randn(4, 6),
                  index=[0, 0, 1, 1],
                  columns=columns)
print(df)

          a                             b                    
          0         1         2         0         1         2
0  0.582804  0.753118 -0.900950 -0.914657 -0.333091 -0.965912
0  0.498002 -0.842624  0.155783  0.559730 -0.300136 -1.211412
1  0.727019  1.522160  1.679025  1.738350  0.593361  0.411907
1  1.253759 -0.806279 -2.177582 -0.099210 -0.839822 -0.211349

我想按索引分组,并在 a 列上使用“min”聚合,在 b 列上使用“sum”聚合。

我知道我可以通过创建一个为每一列指定聚合函数的字典来做到这一点:

agg_dict = {'a': 'min', 'b': 'sum'}
full_agg_dict = {(c, i): agg_dict[c] for c in ['a', 'b'] for i in range(3)}
print(df.groupby(level=0).agg(full_agg_dict))

          a                             b                    
          0         1         2         0         1         2
0  0.498002 -0.842624 -0.900950 -0.354927 -0.633227 -2.177324
1  0.727019 -0.806279 -2.177582  1.639140 -0.246461  0.200558

有没有更简单的方法?似乎应该有一种方法可以在不使用 full_agg_dict 的情况下使用 agg_dict 执行此操作。

最佳答案

我也会使用您的方法。但这是(应该)工作的另一种方式:

(df.stack(level=1)
   .groupby(level=[0,1])
   .agg({'a':'min','b':'sum'})
   .unstack(-1)
)

由于某些原因 groupby(level=[0,1] 对我不起作用,所以我想出了:

(df.stack(level=1)
   .reset_index()
   .groupby(['level_0','level_1'])
   .agg({'a':'min','b':'sum'})
   .unstack('level_1')
)

关于python - Pandas groupby : can I select an agg function by one level of a column MultiIndex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57810172/

相关文章:

python - 如何使用 python 或 matlab 将多个图像堆叠在一起?

python - 为什么分配给 sys.modules[__name__] 后 __name__ 的值会发生变化?

python - Groupby 和值计数类别

python - 找到与 "True"最接近的索引并计算距离 (Pandas)

python - Groupby 类和计数特征中的缺失值

Python3,二进制数据与我需要的表示不同

Python对象交互

python - Pandas 到 Sql Server 的速度 - python 批量插入?

python - pandas - 根据不同数据框中的另一个值获取值

python - 在 Pandas 中创建数据透视表并同时对每周的日期进行分组