Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of categories in DataFrame object?

Tags:

python

pandas

Let say we have a DataFrame object with number of boxes. Each box has a fruit inside 'Apple', 'Banana' or 'Peach'.

How to count how many boxes have 'Apple' or 'Bananas' or 'Peach' inside?

like image 544
Sergei Avatar asked Oct 14 '25 04:10

Sergei


1 Answers

Do you mean something such as:

from collections import Counter
df = pd.DataFrame({'a':['apple','apple','banana','peach', 'banana', 'apple']})

print Counter(df['a'])
>> Counter({'apple': 3, 'banana': 2, 'peach': 1})

You can also use groupby:

df = pd.DataFrame({'a':['apple','apple','banana','peach', 'banana', 'apple']})

print df.groupby(['a']).size()
>> a
   apple     3
   banana    2
   peach     1
like image 58
DeepSpace Avatar answered Oct 17 '25 08:10

DeepSpace