Python Pandas - Get unique values from a column

PythonServer Side ProgrammingProgramming

To get unique values from a column in a DataFrame, use the unique(). To count the unique values from a column in a DataFrame, use the nunique().

At first, import the required library −

import pandas as pd;

Create a DataFrame with 3 columns. We have duplicate values as well −

dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80]
   }
)

Get unique values with the count −

print"\nUnique values from a column ...\n",dataFrame['Car'].unique()
print"\nCount unique values from a column ...\n",dataFrame['Car'].nunique()

Example

Following is the code −

import pandas as pd;

# create a DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80]
   }
)

print"DataFrame ...\n",dataFrame

# get unique values from a column
print"\nUnique values from a column ...\n",dataFrame['Car'].unique()
print"\nCount unique values from a column ...\n",dataFrame['Car'].nunique()

Output

This will produce the following output −

DataFrame ...
       Car       Place   Units
0      BMW      Delhi    100
1     Audi  Bangalore    150
2      BMW  Hyderabad     50
3    Lexus Chandigarh    110
4    Tesla       Pune     90
5    Lexus     Mumbai    120
6  Mustang     Jaipur     80

Unique values from a column ...
['BMW' 'Audi' 'Lexus' 'Tesla' 'Mustang']

Count unique values from a column ...
5
raja
Published on 16-Sep-2021 07:56:00
Advertisements