Search code examples
pandascountseriesmulti-index

Pandas Multiindex count on levels


The data:

index = [('A', 'aa', 'aaa'),
         ('A', 'aa', 'aab'),
         ('B', 'bb', 'bbb'),
         ('B', 'bb', 'bbc'),
         ('C', 'cc', 'ccc')
        ]
values = [0.07, 0.04, 0.04, 0.06, 0.07]

s = pd.Series(data=values, index=pd.MultiIndex.from_tuples(index))

s
A  aa  aaa    0.07
       aab    0.04
B  bb  bbb    0.04
       bbc    0.06
C  cc  ccc    0.07

To get a mean of first two levels is easy:

s.mean(level=[0,1])

Result:

A  aa    0.055
B  bb    0.050
C  cc    0.070

But to get a count on first two levels does not work the same:

#s.count(level=[0,1]) # does not work

I can get around with:

s.reset_index().groupby(['level_0', 'level_1']).size()

level_0  level_1
A        aa         2
B        bb         2
C        cc         1

But there must be a cleaner way to get the same result? Am I missing something obvious?


Solution

  • It seems bug, you can use:

    print (s.groupby(level=[0,1]).size())
    #with exclude NaNs
    #print (s.groupby(level=[0,1]).count())
    A  aa    2
    B  bb    2
    C  cc    1
    dtype: int64