zork
zork

Reputation: 2135

Python Pandas: Counting element occurrences in series

How to find series element counts? Using this code:

import pandas as pd

d = { 'x' : [1,2,2,2,3,4,5,5,7] }
df = pd.DataFrame(d)
cnt1 = len(df[df.x == 1])
cnt2 = len(df[df.x == 2])
cnt3 = len(df[df.x == 3])
...

does not help much. Is there any way to count element occurrences so result would be a dictionary with 'element, count' pairs, like this:

cnts = {'1':1, '2': 3, '3':1, ...}

or in some other structure easy to lookup and iterate ?

Upvotes: 2

Views: 14002

Answers (2)

Zero
Zero

Reputation: 76917

Here are two ways to get the freq-distribution

In [8]: df.groupby('x').size().to_dict()
Out[8]: {1: 1, 2: 3, 3: 1, 4: 1, 5: 2, 7: 1}

In [9]: df['x'].value_counts().to_dict()
Out[9]: {1: 1, 2: 3, 3: 1, 4: 1, 5: 2, 7: 1}

Upvotes: 1

user2285236
user2285236

Reputation:

You can use value_counts. It returns a Series which can be looked up like a dictionary and you can iterate over it:

df['x'].value_counts(sort=False)
Out: 
1    1
2    3
3    1
4    1
5    2
7    1
Name: x, dtype: int64

If you want, you can convert it to a dictionary too:

df['x'].value_counts().to_dict()
Out: {1: 1, 2: 3, 3: 1, 4: 1, 5: 2, 7: 1}

Upvotes: 10

Related Questions