1

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)
1
  • Do all the arrays have the same shape? Commented Feb 5, 2018 at 21:19

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.