neversaint
neversaint

Reputation: 63984

How to count occurrence of elements in a single column of Pandas Dataframe

I have the following DF:

import pandas as pd
data = pd.DataFrame({'name' : ['a', 'a', 'b', 'd']})
In [7]: data
Out[7]:
  name
0    a
1    a
2    b
3    d

What I want to do is to summarize

a 2
b 1
d 1

How can I do it? Tried this but not good:

g = data.groupby('name')
g.count()

Upvotes: 1

Views: 11463

Answers (1)

shivsn
shivsn

Reputation: 7828

hope this helps use value_counts:

data = pd.DataFrame({'name' : ['a', 'a', 'b', 'd']})

In [14]: data['name'].value_counts()
Out[14]: 
a    2
b    1
d    1
dtype: int64

or As you have tried using groupby:

g=data.groupby('name')['name']

g.count()
Out[25]: 
name
a    2
b    1
d    1
Name: name, dtype: int64

Upvotes: 8

Related Questions