How to list unique values in Pandas DataFrame in Python

How to list unique values in Pandas DataFrame in Python

Pandas is a powerful data manipulation library in Python that is widely used in data analysis and data science. One of the common tasks that is performed using Pandas is listing unique values in a DataFrame. In this blog, we will discuss how to list unique values in a Pandas DataFrame in Python.

The first method we can use is the unique() method. This method is used to return unique values in a DataFrame. We can use this method on any column of the DataFrame to get unique values in that column. For example, if we have a DataFrame named df, we can use the following code to get the unique values in the column “Name”:

unique_names = df['Name'].unique()
print(unique_names)

 

The second method we can use is the value_counts() method. This method is used to return a Series containing counts of unique values. We can use this method on any column of the DataFrame to get the count of unique values in that column. For example, if we have a DataFrame named df, we can use the following code to get the count of unique values in the column “Age”:

unique_age_count = df['Age'].value_counts()
print(unique_age_count)

 

The third method we can use is the nunique() method. This method is used to return the number of unique elements in the DataFrame or a column of the DataFrame. We can use this method on any column of the DataFrame to get the number of unique values in that column. For example, if we have a DataFrame named df, we can use the following code to get the number of unique values in the column “City”:

unique_city_count = df['City'].nunique()
print(unique_city_count)

 

The fourth method we can use is the drop_duplicates() method. This method is used to return a new DataFrame with duplicate rows removed. We can use this method on the DataFrame to get a new DataFrame with unique rows only. For example, if we have a DataFrame named df, we can use the following code to get a new DataFrame with unique rows:

unique_df = df.drop_duplicates()
print(unique_df)

 

In conclusion, Pandas provides several ways to list unique values in a DataFrame. Depending on the requirement, we can use any of the above-mentioned methods to achieve the task. These methods are simple to use and provide flexibility in terms of handling unique values in a DataFrame.

In this Learn through Codes example, you will learn: How to list unique values in Pandas DataFrame in Python.



Find more … …

Python Example – Write a Python program to get unique values from a list

Excel formula for Beginners – How to find Unique values by count in Excel

Excel Example for Data Analyst – Count unique dates

Essential Gigs