Convert Nested List to Multidimensional NumPy Array in Python

In this tutorial, you are going to learn how to convert nested lists to multidimensional NumPy arrays with the help of simple Python programming.

Converting a nested list into NumPy arrays is useful because NumPy is so fast and high-performance Python library to performs resource-heavy mathematical tasks. That’s the reason you may need to perform this conversion.

Well, you can achieve this task in two different ways that are discussed below:

Using numpy.array() method

Below is given how to convert a nested list into a NumPy array using the numpy array() method:

import numpy as np

# initializing a list 
my_list = [[7, 13, 23],
  [ 11, 3, 15]] 

# converting the above list to array 
my_rray = np.array(my_list) 

# print list 
print ( my_list) 

# print array 
print ( my_rray) 
[[7, 13, 23], [11, 3, 15]]
[[ 7 13 23]
[11 3 15]]

In the above program, we first import the numpy library. Next, we created our nested list my_list. After that, we converted it to an array using the NumPy array() method. Finally, we print both the list and array in order to see the result.

Using numpy.asarray() method

Below is an example of a Python program using the NumPy asarray() method to convert our NumPy nested list into an array:

import numpy as np

# creating the list 
my_list = [[10, 16, 23],[ 9, 21, 15],[ 17, 6, 19],[ 11, 34, 3]] 

# list to array conversion
my_rray = np.asarray(my_list) 

# print list 
print ( my_list) 

# print array 
print ( my_rray) 
[[10, 16, 23], [9, 21, 15], [17, 6, 19], [11, 34, 3]]
[[10 16 23]
[ 9 21 15]
[17 6 19]
[11 34 3]]

Leave a Reply

Your email address will not be published. Required fields are marked *