Python - Finding count of distinct elements in dataframe in each column

Learn, how can we find count of distinct elements in dataframe in each column? By Pranit Sharma Last updated : September 29, 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

Given a Pandas DataFrame, we have to find count of distinct elements in dataframe in each column.

When we access a DataFrame, we always find similar values multiple times which causes trouble in effective data analysis, for this purpose, we need to find the count of distinct elements in each column.

Count of distinct elements in dataframe

To count the distinct elements of DataFrame in each column, we need to focus on the unique elements or the count of each element only once. For this purpose, we will use pandas.DataFrame.nunique() method. The method returns the number of unique values for each column.

Let us understand with the help of an example,

Python program to find count of distinct elements in dataframe in each column

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'A':[0,0,1,2,2,3],
    'B':[1,2,3,4,5,6],
    'C':[0,0,1,1,1,2]
}

# Creating DataFrames
df = pd.DataFrame(d1)

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

# Getting count of different elements
result = df.nunique()

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

Output

The output of the above program is:

Example: Count of distinct elements in dataframe in each column

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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