The Wayback Machine - https://web.archive.org/web/20240530132030/https://www.geeksforgeeks.org/get-unique-values-from-a-column-in-pandas-dataframe/
Open In App

Get unique values from a column in Pandas DataFrame

Last Updated : 01 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The unique() function removes all duplicate values on a column and returns a single value for multiple same values. In this article, we will discuss how we can get unique values from a column in Pandas DataFrame.

Creating a Pandas Dataframe with Duplicate Elements

Create a sample Pandas dataframe with a dictionary of lists, say columns names are A, B, C, D, and E with duplicate elements.

Python3




# Import pandas package
import pandas as pd
 
# create a dictionary with five fields each
data = {
    'A': ['A1', 'A2', 'A3', 'A4', 'A5'],
    'B': ['B1', 'B2', 'B3', 'B4', 'B4'],
    'C': ['C1', 'C2', 'C3', 'C3', 'C3'],
    'D': ['D1', 'D2', 'D2', 'D2', 'D2'],
    'E': ['E1', 'E1', 'E1', 'E1', 'E1']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)


Get unique values from a column in Pandas DataFrame

Below are some examples by which we can get the unique values of a column in this dataframe.

  • Get the Unique Values of ‘B’ Column
  • Get the Unique Values of ‘E’ Column
  • Get Number of Unique Values in a Column
  • Using set() to Eliminate Duplicate Values from a Column
  • Using pandas.concat() and Unique() Methods
  • Using Series.drop_duplicates()

Get the Unique Values of ‘B’ Column

In this example, we are retrieving and printing the unique values from the ‘B’ column using the unique() method. The resulting unique values are ['B1', 'B2', 'B3', 'B4'].

Python3




# Import pandas package
import pandas as pd
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Get the unique values of 'B' column
df.B.unique()


Output

array(['B1', 'B2', 'B3', 'B4'], dtype=object)

Get the Unique Values of Pandas in ‘E’ Column

In this example, we create a pandas DataFrame from a dictionary and then retrieves the unique values from the ‘E’ column using the unique() method. The resulting unique values are ['E1'].

Python3




# Import pandas package
import pandas as pd
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Get the unique values of 'E' column
df.E.unique()


Output

array(['E1'], dtype=object)

Get Number of Unique Values in a Column

In this example, we create a pandas DataFrame from a dictionary and then calculates and prints the number of unique values in the ‘C’ column, excluding NaN values. The result is 3, indicating there are three unique values in column ‘C’.

Python3




# Import pandas package
import pandas as pd
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Get number of unique values in column 'C'
df.C.nunique(dropna=True)


Output

3

Eliminate Duplicate Values from a Column using set()

In this example, we create a pandas DataFrame from a dictionary and then uses the set() function to extract unique values from column ‘C’, eliminating duplicates. The resulting set, {'C1', 'C2', 'C3'}, represents the unique values in column ‘C’.

Python3




# Import pandas package
import pandas as pd
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Use set() to eliminate duplicate values in column 'C'
unique_values_set = set(df['C'])
 
# Print the unique values
print(unique_values_set)


Output

{'C1', 'C2', 'C3'}

Using pandas.concat() and Unique() Methods

In this example, we create a pandas DataFrame from a dictionary and then concatenates unique values from all columns using pd.concat(). The resulting NumPy array, when printed, displays all unique values from columns ‘A’ to ‘E’.

Python3




# Import pandas package
import pandas as pd
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Use pd.concat() to concatenate all columns and then apply unique()
unique_values_all_columns = pd.concat([df[col].unique() for col in df.columns])
 
# Print the unique values
print(unique_values_all_columns)


Output

['A1' 'A2' 'A3' 'A4' 'A5' 'B1' 'B2' 'B3' 'B4' 'C1' 'C2' 'C3' 'D1' 'D2' 'E1']

Using Series.drop_duplicates()

In this example, we create a pandas DataFrame from a dictionary and removes duplicates from columns ‘A’ and ‘D’ using the drop_duplicates() method. The resulting DataFrame, when printed, displays the unique values in columns ‘A’ and ‘D’, with NaN values where duplicates were removed from ‘D’.

Python3




# Import pandas package
import pandas as pd
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Use drop_duplicates() to remove duplicates from columns 'A' and 'D'
df['A'] = df['A'].drop_duplicates()
df['D'] = df['D'].drop_duplicates()
 
# Print the DataFrame after removing duplicates from columns 'A' and 'D'
print(df)


Output

    A   B   C   D   E
0  A1  B1  C1  D1  E1
1  A2  B2  C2  D2  E1
2  A3  B3  C3 NaN  E1
3  A4  B4  C3 NaN  E1
4  A5  B4  C3 NaN  E1



Previous Article
Next Article

Similar Reads

Getting Unique values from a column in Pandas dataframe
Let's see how can we retrieve the unique values from pandas dataframe. Let's create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. # import pandas as pd import pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csv record = pd.read_csv(gapmi
2 min read
Get column index from column name of a given Pandas DataFrame
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together. Syntax: DataFrame.columns Return: column names index Syntax: Index.get_loc(key, method=None, tolerance=None) Return: loc : int if unique index, slice if monotonic index, els
2 min read
Get n-smallest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-smallest values from a particular column in Pandas DataFrame. Observe this dataset first. We'll use 'Age', 'Weight' and 'Salary' columns of this data in order to get n-smallest value
1 min read
Get n-largest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-largest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values
1 min read
Get a list of a particular column values of a Pandas DataFrame
In this article, we'll see how to get all values of a column in a pandas dataframe in the form of a list. This can be very useful in many situations, suppose we have to get the marks of all the students in a particular subject, get the phone numbers of all the employees, etc. Let's see how we can achieve this with the help of some examples. Pandas
3 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Concatenate Column Values in Pandas DataFrame?
Many times we need to combine values in different columns into a single column. There can be many use cases of this, like combining first and last names of people in a list, combining day, month, and year into a single column of Date, etc. Now we'll see how we can achieve this with the help of some examples. Example 1: In this example, we'll combin
2 min read
Replace all the NaN values with Zero's in a column of a Pandas dataframe
Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it. DataFrame.fillna(): This method is used to fill null or null values with a specific value. Syntax: DataFrame.fillna(self,
3 min read
Ways to filter Pandas DataFrame by column values
Filtering a Pandas DataFrame by way of column values is a commonplace operation while running with information in Python. You can use various methods and techniques to achieve this. Here are numerous ways to filter out a Pandas DataFrame through column values. In this post, we will see different ways to filter Pandas Dataframe by column values. Fir
3 min read