Pandas hierarchical indexing of unique values

Let's say I have a series:

A  a  1
   b  1
B  c  5
   d  8
   e  5

      

where the first two columns together are the hierarchical index. I want to find how many unique values ​​for an index level=0

, for example, this output should be A 1; B 2

. How can this be done easily? Thank!

+3


source to share


1 answer


groupby

at level 0 and then call .nunique

on the column:



>>> df
     val
A a    1
  b    1
B c    5
  d    8
  e    5
>>> df.groupby(level=0)['val'].nunique()
A    1
B    2
Name: val, dtype: int64

      

+4


source







All Articles