11.1 C
London
Sunday, July 7, 2024
HomePandas in PythonDataFrame Functions in PythonPandas: How to Find Unique Values in a Column

Pandas: How to Find Unique Values in a Column

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

The easiest way to obtain a list of unique values in a pandas DataFrame column is to use the unique() function.

This tutorial provides several examples of how to use this function with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C'],
                   'conference': ['East', 'East', 'East', 'West', 'West', 'East'],
                   'points': [11, 8, 10, 6, 6, 5]})

#view DataFrame
df

        team	conference  points
0	A	East	    11
1	A	East	    8
2	A	East	    10
3	B	West	    6
4	B	West	    6
5	C	East	    5

Find Unique Values in One Column

The following code shows how to find the unique values in a single column of the DataFrame:

df.team.unique()

array(['A', 'B', 'C'], dtype=object)

We can see that the unique values in the team column include “A”, “B”, and “C.”

Find Unique Values in All Columns

The following code shows how to find the unique values in all columns of the DataFrame:

for col in df:
  print(df[col].unique())

['A' 'B' 'C']
['East' 'West']
[11  8 10  6  5]

Find and Sort Unique Values in a Column

The following code shows how to find and sort by unique values in a single column of the DataFrame:

#find unique points values
points = df.points.unique()

#sort values smallest to largest
points.sort()

#display sorted values
points

array([ 5,  6,  8, 10, 11])

Find and Count Unique Values in a Column

The following code shows how to find and count the occurrence of unique values in a single column of the DataFrame:

df.team.value_counts()

A    3
B    2
C    1
Name: team, dtype: int64

Additional Resources

How to Select Unique Rows in a Pandas DataFrame
How to Find Unique Values in Multiple Columns in Pandas

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories