1

For the dataframe as below

     animal    direction

0    monkey    north
1    frog      north
2    monkey    east
3    zebra     west
....

I would like to count the number of animals presented in this dataframe to have the below dataframe

     animal     count

0    monkey     3
1    frog       9
2    zebra      4
3    elephant   11
....

How can I achieve this? I tried value_counts(), and groupby but with my knowledge I couldn't quite achieve what I wanted... Thank you for help.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
James Lee
  • 67
  • 5
  • or this [get-statistics-for-each-group-such-as-count-mean-etc-using-pandas-groupby](https://stackoverflow.com/questions/19384532/get-statistics-for-each-group-such-as-count-mean-etc-using-pandas-groupby) – sjd Oct 16 '19 at 04:00
  • What's wrong with `.value_counts()`? – gosuto Oct 16 '19 at 04:15
  • Thank you, I found the solution from sjd's link! – James Lee Oct 16 '19 at 04:16
  • @jorijnsmit After doing the ```.value_counts()``` and performing ```reset_index()``` to have the index, it was weird. It gave me a dummie column name "index" and I was not able to change the name of that. When I tried to change the name, it'll lose the index I assigned by ```reset_index()```... – James Lee Oct 16 '19 at 04:18
  • Please answer your own question if you have found a solution. – gosuto Oct 16 '19 at 04:20
  • @jorijnsmit oh, sorry didn't know there was such a thing..... – James Lee Oct 16 '19 at 04:22

1 Answers1

0

df.groupby(['col1']).size().reset_index(name='counts')

This method worked beautifully. Thank you.

James Lee
  • 67
  • 5