I got a Pandas dataframe
and want to groupby
and count on 'animal' column to fetch the top 3 as a list:
> df
animal age weight length
0 hamster 5 13 2
1 hamster 14 11 4
2 cat 3 14 4
3 cat 5 6 4
4 snake 7 14 8
5 cat 4 12 5
6 hamster 11 12 9
7 snake 14 9 7
8 hamster 1 5 9
9 alligator 4 13 2
10 snake 12 7 6
11 hamster 14 10 2
12 snake 7 14 7
13 alligator 4 10 2
> df.groupby("animal")['animal'].count().nlargest(3)
animal
hamster 5
snake 4
cat 3
Is this an efficient way and also how do I go about convert the resulting top 3 to an ordered list ie, ['hamster', 'snake', 'cat']
?