pandas 分组多索引熊猫数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/18689474/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
group multi-index pandas dataframe
提问by silencer
Is it possible to groupby a multi-index (2 levels) pandas dataframe by one of the multi-index levels ?
是否可以按多索引级别之一对多索引(2 级)Pandas数据框进行分组?
The only way I know of doing it is to reset_index on a multiindex and then set index again. I am sure there is a better way to do it, and I want to know how.
我知道这样做的唯一方法是在多索引上重置索引,然后再次设置索引。我相信有更好的方法可以做到这一点,我想知道如何做。
回答by elyase
Yes, use the levelparameter. Take a look here. Example:
是的,使用level参数。看看这里。例子:
In [26]: s
first  second  third
bar    doo     one      0.404705
               two      0.577046
baz    bee     one     -1.715002
               two     -1.039268
foo    bop     one     -0.370647
               two     -1.157892
qux    bop     one     -1.344312
               two      0.844885
dtype: float64
In [27]: s.groupby(level=['first','second']).sum()
first  second
bar    doo       0.981751
baz    bee      -2.754270
foo    bop      -1.528539
qux    bop      -0.499427
dtype: float64

