总结 pandas 系列中的多指标水平 [英] Summing over a multiindex level in a pandas series
本文介绍了总结 pandas 系列中的多指标水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用python中的Pandas软件包,我想对具有3级多索引的系列中的一个级别进行求和(边际化),以生成具有2级多索引的系列.例如,如果我有以下内容:
Using the Pandas package in python, I would like to sum (marginalize) over one level in a series with a 3-level multiindex to produce a series with a 2 level multiindex. For example, if I have the following:
ind = [tuple(x) for x in ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']]
mi = pd.MultiIndex.from_tuples(ind)
data = pd.Series([264, 13, 29, 8, 152, 7, 15, 1], index=mi)
A B C 264
c 13
b C 29
c 8
a B C 152
c 7
b C 15
c 1
我想对变量C求和以产生以下输出:
I would like to sum over the variable C to produce the following output:
A B 277
b 37
a B 159
b 16
熊猫最好的方法是什么?
What is the best way in Pandas to do this?
推荐答案
如果您始终希望在前两个级别进行汇总,那么这很简单:
If you know you always want to aggregate over the first two levels, then this is pretty easy:
In [27]: data.groupby(level=[0, 1]).sum()
Out[27]:
A B 277
b 37
a B 159
b 16
dtype: int64
这篇关于总结 pandas 系列中的多指标水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文