In this short guide, I'll show you how to count occurrences of a specific value in Pandas. Whether you want to count values in a single column or across the whole DataFrame, this guide has you covered.
(1) Count occurrences in a single column
df['column_name'].value_counts().get('target_value', 0)
(2) Count occurrences across the entire DataFrame
(df == 'target_value').sum().sum()
(3) Count occurrences using .shape
df[df['column_name'] == 'target_value'].shape[0]
(4) Count occurrences using len()
len(df[df['column_name'] == 'target_value'])
(5) Count occurrences using .query()
df.query('column_name == "target_value"').column_name.count()
(6) Count occurrences using boolean mask with .sum()
(df['column_name'] == 'target_value').sum()
(7) Count occurrences using NumPy array
(df['column_name'].values == 'target_value').sum()
1: Example DataFrame
Let's create a sample DataFrame:
import pandas as pd
data = {
'A': ['apple', 'banana', 'apple', 'orange', 'banana'],
'B': ['apple', 'apple', 'banana', 'banana', 'apple']
}
df = pd.DataFrame(data)
Output:
A | B | |
---|---|---|
0 | apple | apple |
1 | banana | apple |
2 | apple | banana |
3 | orange | banana |
4 | banana | apple |
2: Count Occurrences in a Column
To count occurrences of "apple"
in column A
:
df['A'].value_counts().get('apple', 0)
Output:
2
3: Count Occurrences Across the Entire DataFrame
To count "apple"
occurrences in all columns:
(df == 'apple').sum().sum()
Output:
4
4: Count Multiple Values
If you want to count multiple values in a column:
df['A'].value_counts()
Output:
banana 2
apple 2
orange 1
Name: A, dtype: int64
Conclusion
In this guide, we covered:
- Counting occurrences of a value in a specific column
- Counting occurrences across the entire DataFrame
- Using
.value_counts()
for frequency analysis