Python - Create a set from a series in pandas

Given a pandas series, we have to convert it into a set. By Pranit Sharma Last updated : September 27, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

A series in pandas contains a single list that can store heterogeneous types of data, because of this, a series is also considered a 1-dimensional data structure.

When we analyze a series, each value can be considered as a separate row of a single column, both series and DataFrame can be created either with the list or with the help of a dictionary, in the case of series, there will be only one key in the dictionary but there may be multiple keys in case of DataFrame.

Sets are used to store multiple items which are heterogeneous. Just like list, tuple, and dictionary, the set is another built-in data type in python which is used to store elements. Elements inside a set are unique that is there is only 1 occurrence of each element inside a set.

Problem statement

Given a pandas series, we have to convert it into a set.

Creating a set from a series in pandas

To create a set from a series in pandas, you have to first find the unique elements using the series.unique() method and then convert it into a set by using the set() method which is an inbuilt method in Python.

Let us understand with the help of an example,

Python program to create a set from a series in pandas

# Importing pandas package
import pandas as pd

# Creating a series
s = pd.Series([1, 2, 3, 1, 1, 4])

# Display original series
print("Original Series:\n",s,"\n")

# finding unique element
s = s.unique()

# Display final result
print("Converted set:\n",set(s))

Output

The output of the above program is:

Example: Set from a series in pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.