Skip to content

Count the frequency that a value occurs in a dataframe column โ€‹

Here is an example code snippet that counts the frequency of values in a column of a Pandas DataFrame:

Count the frequency of values in a column of a Pandas DataFrame in Python

python
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3, 1, 2, 3, 1, 2, 3],
                   'B': ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']})

# count the frequency of values in column 'A'
value_counts = df['A'].value_counts()

print(value_counts)

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

This will output:

output

console
1    3
2    3
3    3
Name: A, dtype: int64

You can also use .value_counts(normalize=True) to get the frequency as a percentage.

Dual-run preview โ€” compare with live Symfony routes.