3

I'm trying to count the number of unique items grouped by a value and sorted by the count of the unique items per group.

For example

   A  B
0  C  A
1  C  C
2  D  C
3  D  J
4  D  F
5  E  C
6  E  C

The output should show

   A  count
0  D      3
1  C      2
2  E      1

I'm currently using the below where I can get the unique count but not the sorting

df.groupby('A').B.nunique()
Zero
  • 74,117
  • 18
  • 147
  • 154
GlenCloncurry
  • 457
  • 3
  • 5
  • 15

1 Answers1

7

I think you need add sort_values + reset_index:

df = df.groupby('A')['B'].nunique().sort_values(ascending=False).reset_index(name='count')
print (df)
   A  count
0  D      3
1  C      2
2  E      1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252