Skip to main content

Python Pandas Get Column Unique Values From Dataframe (Example)

Generating column unique values from a dataframe.

Dataframe has "unique" method which returns the required unique values. Creating a new dataframe with dictionary (which has duplicate data)

# importing pandas
import pandas as pd


# animal_data_with_duplicates dictionary
animal_data_with_duplicates = {
    "Name": ["Cat", "Dog", "Cow","Tiger","Cat"],
    "Speed": [15, 12, 10,20,15],
    "Sound": ["Meow", "Woof", "Mooo","Roar","Meow"],
}

#creating a dataframe using the animal_data_with_duplicates dictionary
animal_with_duplicates_df = pd.DataFrame(animal_data_with_duplicates)

#printing animal_with_duplicates_df
print("animal_with_duplicates_df \n", animal_with_duplicates_df)
animal_with_duplicates_df Name Speed Sound 0 Cat 15 Meow 1 Dog 12 Woof 2 Cow 10 Mooo 3 Tiger 20 Roar 4 Cat 15 Meow

#generating unique values from "Name" column
unique_names = animal_with_duplicates_df["Name"].unique()

print("unique_names \n", unique_names)

unique_names ['Cat' 'Dog' 'Cow' 'Tiger']

Comments

Topics

Show more