Pandas Multiindex count on levels

谁都会走 提交于 2021-02-05 10:59:47

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/58432672/pandas-multiindex-count-on-levels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!