Sammuel Brown
Sammuel Brown

Reputation: 11

Converting a list of numpy array to a single int numpy array

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?

Upvotes: 1

Views: 946

Answers (2)

hpaulj
hpaulj

Reputation: 231738

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)

Upvotes: 0

Till Hoffmann
Till Hoffmann

Reputation: 9887

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.

Upvotes: 1

Related Questions