Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas hierarchical indexing unique values

Tags:

python

pandas

Say I have series:

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

where first two columns together is the hierarchical index. I want to find how many unique values are for index level=0, e.g., in this output should be A 1; B 2. How can this be done easily? Thanks!

like image 254
hovnatan Avatar asked Dec 05 '25 09:12

hovnatan


1 Answers

groupby on 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
like image 142
behzad.nouri Avatar answered Dec 07 '25 22:12

behzad.nouri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!