Open In App

Create A Set From A Series In Pandas

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined though it may contain various elements. The major advantage of using a set, instead of a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.

Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called indices. Labels need not be unique but must be a hashable type. In this article we will learn the creation of a set from a Pandas Series

We can create a set from a series of pandas using two methods:

  • Using Series.unique() and set() functions
  • Using set() function

Before creating a set from a series in pandas, let's create a pandas series and use it for a demonstration of creating a set from a series in pandas.

Here we are creating a series consisting of 10 numbers with duplicates using the series() function in pandas.

Python3
# Install Pandas using pip install pandas
import pandas as pd

# Create a Pandas Series with duplicated values
ser = pd.Series([10, 20, 30, 10, 40, 30, 50, 20, 60, 40])

# Display the Pandas Series
print(ser)

Output:

0    10
1 20
2 30
3 10
4 40
5 30
6 50
7 20
8 60
9 40
dtype: int64

Using Series.unique() and set() functions

We can create a set from the Pandas series using series.unique() and set() functions. The series.unique() function is applied to the series to obtain the NumPy array containing unique elements and then the set() function is applied to remove any remaining duplicate values and create the set.

Example:

Here, we are creating a set from the series we created using series.unique() and set() functions. We convert our original series to a Numpy array using series.unique() function and then passed the function

Python3
# use series.unique() function
ser2 = ser.unique()
print(ser2)

# using series.unique() & set() function
ser.unique()
ser2 = set(ser)
print(ser2)

Output:

[10 20 30 40 50 60]
{40, 10, 50, 20, 60, 30}

Using set() function

We can directly apply set() function to the pandas series, the set function automatically convert the pandas series into a set.

Python3
# Using set() function to create Set
ser3 = set(ser)
print(ser3)

Output:

{40, 10, 50, 20, 60, 30}

Conclusion:

In conclusion, creating a set from a Pandas Series in Python is a useful technique for data manipulation. In this article, we discussed about different ways to create a set from a pandas series that include Using Series.unique() function, set() functions and explained about how those functions work.


Next Article

Similar Reads