Pandas count number of elements in each column less than x

Given a pandas dataframe, we have to count the number of elements in each column less than x. By Pranit Sharma Last updated : October 03, 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.

Problem statement

Here we are given a dataframe, we have random values let us say 10, and we need to find the total number of values in each column that is less than 10.

Counting the number of elements in each column less than x

For this purpose, we will simply access the values of DataFrame by applying a filter of less than 10, and then we will apply the count() method on the same.

Let us understand with the help of an example,

Python program to count number of elements in each column less than x

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[10,9,8,20,23,30],
    'B':[1,2,7,5,11,20],
    'C':[1,2,3,4,5,90]
}

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

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

# Accessing all the values less than 10 
# and counting them
res = df[df < 10 ].count()

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Count number of elements in each column less than x

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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