1

I have a list of numpy arrays, that I want to convert into a single int numpy array.
For example if I have 46 4 x 4 numpy arrays in a list of dimension 2 x 23, I want to convert it into a single integer numpy array of 2 x 23 x 4 x 4 dimension. I have found a way to do this by going through every single element and using numpy.stack(). Is there any better way?

1
  • So you have a 2x23 list of 4x4 numpy arrays and want to make it one single 4 dimensional numpy array? Commented Jun 20, 2018 at 14:08

2 Answers 2

1

You can simply use np.asarray like so

import numpy as np

list_of_lists = [[np.random.normal(0, 1, (4, 4)) for _ in range(23)] 
                 for _ in range(2)]
a = np.asarray(list_of_lists)
a.shape

The function will infer the shape of the list of lists for you and create an appropriate array.

Sign up to request clarification or add additional context in comments.

Comments

0

Stack works for me:

In [191]: A,B,C = np.zeros((2,2),int),np.ones((2,2),int),np.arange(4).reshape(2,
     ...: 2)
In [192]: x = [[A,B,C],[C,B,A]]
In [193]: 
In [193]: x
Out[193]: 
[[array([[0, 0],
         [0, 0]]), array([[1, 1],
         [1, 1]]), array([[0, 1],
         [2, 3]])], [array([[0, 1],
         [2, 3]]), array([[1, 1],
         [1, 1]]), array([[0, 0],
         [0, 0]])]]
In [194]: np.stack(x)
Out[194]: 
array([[[[0, 0],
         [0, 0]],

        [[1, 1],
         [1, 1]],

        [[0, 1],
         [2, 3]]],


       [[[0, 1],
         [2, 3]],

        [[1, 1],
         [1, 1]],

        [[0, 0],
         [0, 0]]]])
In [195]: _.shape
Out[195]: (2, 3, 2, 2)

stack views x as a list of 2 items, and applies np.asarray to each.

In [198]: np.array(x[0]).shape
Out[198]: (3, 2, 2)

Then adds a dimension, (1,3,2,2), and concatenates on the first axis.

In this case np.array(x) works just as well

In [201]: np.array(x).shape
Out[201]: (2, 3, 2, 2)

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.