Group a multi-indexed pandas dataframe by one of its levels?

后端 未结 2 1101
礼貌的吻别
礼貌的吻别 2020-12-18 19:15

Is it possible to groupby a multi-index (2 levels) pandas dataframe by one of the multi-index levels ?

The only way I know of doing it is to reset_index on a mult

相关标签:
2条回答
  • 2020-12-18 19:23

    Yes, use the level parameter. Take a look here. Example:

    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
    
    0 讨论(0)
  • 2020-12-18 19:37

    If there are already multiple index available, then simply position number can be used instead of column name:

    df = df.groupby(level=[0,1]).size()
    
    0 讨论(0)
提交回复
热议问题