Reputation: 107
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
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