BilginAksoy
BilginAksoy

Reputation: 107

Convert a Python List to an Array

I'm trying to convert a list to a numpy array. My list's length is 64, each element of the list is an numpy array(8 x 8). My output should be a numpy array of (8,8,1,64). How can I convert list to numpy array.

type(dct)
>>>list

len(dct)
>>>64

type(dct[0])
>>>numpy.ndarray

dct[0].shape
>>>(8,8)

Upvotes: 1

Views: 1555

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477883

You call the numpy.array constructor:

from numpy import array

the_array = array(dct)

But this only works if all the elements of the list have the same shape (if not, we still can use an array(..), but then we get a 1D array of objects.

For example:

>>> dct = [array([1, 4, 2, 5]), array([1, 3, 0, 2])]
>>> array(dct)
array([[1, 4, 2, 5],
       [1, 3, 0, 2]])

In case the elements have a different shape:

>>> dct = [array([1, 4, 2, 5]), array([1, 3, 0])]
>>> array(dct)
array([array([1, 4, 2, 5]), array([1, 3, 0])], dtype=object)

Upvotes: 4

Related Questions