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:
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.
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()
The unique
function returns a list containing all unique elements only.
The resultant list is not sorted.
The example shows how we can use the unique
function in pandas:
import pandas as pd# Creating a dataframedf = 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 countriesprint(df["Country"].unique())# Finding unique rankingsprint(df["Rank"].unique())
Free Resources