How to Convert a Set to a NumPy Array?

Given a Python set, we have to convert it into a NumPy array.
By Pranit Sharma Last updated : December 25, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

The set is one of the 4 built-in data types in Python and is used to store heterogeneous types of elements. A set can not contain repeated values hence the occurrence of any value in a set is always 1.

Problem statement

Suppose that we are given some values on which we perform some operation and store the result into a set that we need to convert into a numpy array.

Converting a Set to a NumPy Array

For this purpose, we will first convert the set into a list using the list() function and then we will convert this list into a numpy array using the array function.

Syntax

Below is the syntax to convert a set into a NumPy array:

arr = np.array(list(set_name))

Let us understand with the help of an example,

Python Program to Convert a Set to a NumPy Array

# Import numpy
import numpy as np

# Defining some values
vals = np.array([50,80,73,83])

# Performing some operation and 
# storing result in a set
s = set(vals*10)

# Display set
print("Set:\n",s,"\n")

# Converting set into numpy array
arr = np.array(list(s))

# Display result
print("Result:\n",arr,"\n")

Output

The output of the above program is:

Example: How to Convert a Set to a NumPy Array?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





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