Python Pandas - Display unique values present in each column


To display unique values in each column, use the unique() method and set the column within it. At first, import the required library −

import pandas as pd

Create a DataFrame with two columns and duplicate records −

dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', 'Kat', 'Ted'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass']
   }
)

Find unique values by setting each column in the unique() method −

resStudent = pd.unique(dataFrame.Student)
resResult = pd.unique(dataFrame.Result)

Example

Following is the code −

import pandas as pd


# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', 'Kat', 'Ted'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass']
   }
)

print"DataFrame ...\n",dataFrame

# finding unique values
resStudent = pd.unique(dataFrame.Student)
resResult = pd.unique(dataFrame.Result)

print"\nUnique values in Student Column", resStudent
print"\nUnique values in Result Column", resResult

Output

This will produce the following output −

DataFrame ...
   Result   Student
0    Pass      Jack
1    Fail     Robin
2    Pass       Ted
3    Fail     Robin
4    Pass  Scarlett
5    Pass       Kat
6    Pass       Ted

Unique values in Student Column ['Jack' 'Robin' 'Ted' 'Scarlett' 'Kat']

Unique values in Result Column ['Pass' 'Fail']

Updated on: 20-Sep-2021

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements