Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: Counting element occurrences in series

Tags:

python

pandas

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 ?

like image 463
zork Avatar asked Mar 03 '26 10:03

zork


2 Answers

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}

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}
like image 22
Zero Avatar answered Mar 04 '26 22:03

Zero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!