How to find count of distinct elements in dataframe in each column?

Learn, how to find count of distinct elements in dataframe in each column in Python?
Submitted by Pranit Sharma, on February 13, 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.

Finding count of distinct elements in dataframe in each column

For this purpose, we can use nunique() method directly on our dataframe. This method is used to count number of distinct elements in specified axis.

The syntax of nunique() method is:

DataFrame.nunique(axis=0, dropna=True)

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 a dataframe
df = pd.DataFrame(data={'X': [1,1,1], 'Y': [8,8,7], 'Z': [5,0,4]})

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

# Getting count of unique elements
res = df.nunique()

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

Output

The output of the above program is:

Example: How to find 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.