Sergei
Sergei

Reputation: 411

How to count number of categories in DataFrame object?

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?

Upvotes: 4

Views: 12347

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

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

Upvotes: 10

Related Questions