How to list unique values in a Pandas DataFrame?

This recipe helps you list unique values in a Pandas DataFrame.

Objective For ‘How to list unique values in a Pandas DataFrame?’

This step-by-step recipe will show you how to find unique values in Python Dataframe and list them.

How To Check Unique Values in Python Dataframe?

We can easily view the dataframe, and sometimes we find that a few values have been repeated many times in different rows. What should we do if we need to find unique values or categories in the feature? 

This recipe will help you learn how to make a list of unique values in Pandas DataFrame.

Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects

Step 1 - Import the library

import pandas as pd

We have only imported the Pandas library, which is required for this.

Step 2 - Setting up the Data

We have created a dictionary with columns 'Name', 'Year', and 'Episodes' and passed this in pd.DataFrame to create a DataFrame with index. 

data = {'name': ['Sheldon', 'Penny', 'Amy', 'Penny', 'Raj', 'Sheldon'], 'year': [2012, 2012, 2013, 2014, 2014,2012 ], 'episodes': [42, 24, 31, 29, 37, 40]} df = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e','f']) print(df)

Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro

Step 3 - Pandas List Unique Values and Printing it

We can find unique values by unique function in two formats:

  • series.unique(): In this, we have to add the unique function after the series(column) in which we want to find the unique values.

  • pd.unique(): In this, we have to pass the series as a parameter to find the unique values.

We have used both functions for better understanding. 

print(df.name.unique()) print(pd.unique(df['year'])) 

The output of the dataset comes as-

     name  year  episodes

a  Sheldon  2012        42

b    Penny  2012        24

c      Amy  2013        31

d    Penny  2014        29

e      Raj  2014        37

f  Sheldon  2012        40

 

['Sheldon' 'Penny' 'Amy' 'Raj']

 

[2012 2013 2014]

FAQs

  1. How to list unique values in a Pandas DataFrame column?

To convert Pandas unique values to list in a DataFrame column, you can use the unique() method. The unique() method takes a DataFrame column as its input and returns a list of the unique values in the column. For example, the following code lists the unique values in the column_name column of a DataFrame called ‘df’: df['column_name'].unique()

  1. How to list unique values in a Pandas DataFrame row?

To make a Pandas unique list of values in a DataFrame row, you can use the df.stack().unique() method. The df.stack() method stacks the DataFrame rows one on top of the other, and the unique() method returns a list of the unique values in the stacked DataFrame. For example, the following code lists the unique values in each row of a DataFrame called df: df.stack().unique()

  1. How to list unique values in a Pandas DataFrame with multiple columns?

To make a Pandas DataFrame unique list of values in a dataframe with multiple columns, you can use the df.nunique() method. The df.nunique() method takes a list of column names as its input and returns a DataFrame with the number of unique values in each column. For example, the following code lists the number of unique values in the column_name_1 and column_name_2 columns of a DataFrame called df: df[['column_name_1', 'column_name_2']].nunique()

 Join Millions of Satisfied Developers and Enterprises to Maximize Your Productivity and ROI with ProjectPro - Read ProjectPro Reviews Now!  

 

 


Download Materials


What Users are saying..

profile image

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

Classification Projects on Machine Learning for Beginners - 1
Classification ML Project for Beginners - A Hands-On Approach to Implementing Different Types of Classification Algorithms in Machine Learning for Predictive Modelling

AWS MLOps Project for Gaussian Process Time Series Modeling
MLOps Project to Build and Deploy a Gaussian Process Time Series Model in Python on AWS

Machine Learning Project to Forecast Rossmann Store Sales
In this machine learning project you will work on creating a robust prediction model of Rossmann's daily sales using store, promotion, and competitor data.

Build a Collaborative Filtering Recommender System in Python
Use the Amazon Reviews/Ratings dataset of 2 Million records to build a recommender system using memory-based collaborative filtering in Python.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Loan Eligibility Prediction in Python using H2O.ai
In this loan prediction project you will build predictive models in Python using H2O.ai to predict if an applicant is able to repay the loan or not.

Build a Credit Default Risk Prediction Model with LightGBM
In this Machine Learning Project, you will build a classification model for default prediction with LightGBM.

Census Income Data Set Project-Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based oncensus data.

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.