Python - Count occurrences of False or True in a column in pandas

Given a Pandas DataFrame, we need to count the occurrence of bool values in a column in pandas. By Pranit Sharma Last updated : September 26, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

In programming, we sometimes use some specific values that only have two values, either True or False. These values are known as Boolean values. In this article, we are going to count the occurrences of these Boolean values.

Problem statement

Let us suppose, we are having a DatFrame consisting of a column with bool values, we need to count the occurrence of bool values in a column in pandas.

Counting occurrences of False or True in a column in pandas

We will count these bool values with the help of the value_count() method. The value_count() which will return the count of total occurrences of each value and it encapsulates all the similar values into 1 single entity and assigns its corresponding count to a new column.

Let us understand with the help of an example,

Python program to count occurrences of False or True in a column in pandas

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a Dictionary with 25 keys
d = {
    'Name':['Harry','Tony','Peter','Neha','Honey'],
    'Adopted':[True,True,False,False,True]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrames
print("Original DataFrame :\n",df,"\n")

# Counting true and false
result = df.Adopted.value_counts()

# Display result
print("Values counts:\n",result)

Output

The output of the above program is:

Example: Count occurrences of False or True in a column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.