Find unique values in a pandas dataframe, irrespective of row or column location

Given a pandas dataframe, we have to find the unique values, irrespective of row or column location. By Pranit Sharma Last updated : September 30, 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

Suppose we have a pandas DataFrame, by this, we mean that if there are 50 unique values in a DataFrame then we need to find those unique values and not the total count of unique values.

Finding unique values, irrespective of row or column location

For this purpose, we will first use df.values.ravel() method upon which we will use unique() method. The ravel() function returns the flattened underlying data as a ndarray.

Let us understand with the help of an example,

Python program to find the unique values in a pandas dataframe, irrespective of row or column location

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame(np.random.randint(50,100,size=100).reshape(10,10))

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

# Getting unique values
res =  pd.Series(df.values.ravel()).unique()

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

Output

The output of the above program is:

Find unique values in a pandas dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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