You can use the following basic syntax to count the occurrences of True and False values in a column of a pandas DataFrame:
df['my_boolean_column'].value_counts()
This will count the occurrences of both True and False values.
If you only want to count one of the specific values, you can use the following syntax:
#count occurrences of True df['my_boolean_column'].values.sum() #count occurrences of False (~df['my_boolean_column']).values.sum()
The following example shows how to use this syntax in practice.
Example: Count Occurrences of True and False in Pandas
Suppose we have the following pandas DataFrame that contains information about various basketball players:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C', 'C'], 'points': [18, 22, 19, 14, 14, 28, 20], 'all_star': [True, False, False, True, False, True, True]}) #view DataFrame print(df) team points all_star 0 A 18 True 1 A 22 False 2 A 19 False 3 B 14 True 4 B 14 False 5 C 28 True 6 C 20 True
We can use the value_counts() function to count the occurrences of both True and False values in the all_star column:
#count occurrences of True and False in all_star column
df['all_star'].value_counts()
True 4
False 3
Name: all_star, dtype: int64
From the output we can see:
- The value True occurs 4 times in the all_star column.
- The value False occurs 3 times in the all_star column.
You can also use the following syntax to only count the occurrences of True:
#count occurrences of True in all_star column
df['all_star'].values.sum()
4
And you can use the following syntax to only count the occurrences of False:
#count occurrences of False in all_star column
(~df['all_star']).values.sum()
3
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
Pandas: How to Use GroupBy and Value Counts
Pandas: How to Use GroupBy with Bin Counts
Pandas: How to Count Values in Column with Condition