Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

What is the unique function in pandas?

Hassaan Waqar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The pandas library in Python is used to work with data frames that structure data in rows and columns. It is widely used in data analysis and machine learning.

The unique function in pandas is used to find the unique values from a series.

A series is a single column of a data frame.

The illustration below shows how we can use the unique function:

How does the unique function work

We can use the unique function on any possible set of elements in Python. It can be used on a series of strings, integers, tuples, or mixed elements.

Syntax

The syntax of the unique function is as follows:

pd.unique(pd.Series([2, 1, 3, 3]))

We can use it for a data frame as follows:

dataframe["column"].unique()

Return value

The unique function returns a list containing all unique elements only.

The resultant list is not sorted.

Example

The example shows how we can use the unique function in pandas:

import pandas as pd
# Creating a dataframe
df = pd.DataFrame({'Sports': ['Football', 'Cricket', 'Baseball', 'Basketball',
'Tennis', 'Table-tennis', 'Archery', 'Swimming', 'Boxing'],
'Player': ["Messi", "Afridi", "Chad", "Johnny", "Federer",
"Yong", "Mark", "Phelps", "Khan"],
'Country': ["Argentina", "Pakistan", "England", "England", "Switzerland",
"China", "China", "USA", "Pakistan" ],
'Rank': [1, 9, 7, 12, 1, 2, 11, 1, 1] })
# Finding unique countries
print(df["Country"].unique())
# Finding unique rankings
print(df["Rank"].unique())

RELATED TAGS

pandas
python

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring