Boris
Boris

Reputation: 301

4D array from 2D arrays

I have certain number of Numpy arrays with the shape

print(x.shape)
>>>(256,256)

How can I stack them so that the shape is

print(y.shape)
>>>(certainnumber,256,256,1)

I've been trying with np.stack and np.concatenate but I only get out of axis errors or stuff like

print(y.shape)
>>>(anothernumber,256) 

Upvotes: 3

Views: 222

Answers (3)

jakevdp
jakevdp

Reputation: 86310

You can add an axis argument to np.stack to specify which axis you want to stack along:

arrs = [np.random.rand(256, 256) for i in range(11)]
out = np.stack(arrs, axis=0)
out.shape
# (11, 256, 256)

(Note that axis defaults to zero).

If you need to add a one at the end of the shape, then use a newaxis

out[..., np.newaxis].shape
(11, 256, 256, 1)

Upvotes: 1

Divakar
Divakar

Reputation: 221514

Method #1

Here's one with np.stack -

np.stack(list_of_arrays)[...,None]

Method #2

You can prepend a new axis with None/np.newaxis for each of those arrays and concatenate along the first axis for (certainnumber,256,256) shape, like so -

np.concatenate([i[None] for i in list_of_arrays],axis=0)

Then, add new axis as the trailing one for the final (certainnumber,256,256,1) shape, like so -

np.concatenate([i[None] for i in list_of_arrays],axis=0)[...,None]

Sample runs

In [32]: a = np.random.rand(3,4)

In [33]: b = np.random.rand(3,4)

In [34]: list_of_arrays = [a,b]

In [42]: np.stack(list_of_arrays)[...,None].shape
Out[42]: (2, 3, 4, 1)

In [35]: np.concatenate([i[None] for i in list_of_arrays],axis=0)[...,None].shape
Out[35]: (2, 3, 4, 1)

Upvotes: 3

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

Assuming you have your arrays in some sort of container (you can always put them in a container):

>>> ax = [np.random.randint(0, 10, (3,3)) for _ in range(4)]
>>> ax
[array([[0, 3, 1],
       [4, 2, 4],
       [2, 2, 8]]), array([[8, 4, 6],
       [7, 1, 4],
       [8, 9, 8]]), array([[6, 3, 8],
       [4, 6, 8],
       [2, 2, 9]]), array([[1, 8, 1],
       [0, 9, 2],
       [9, 2, 3]])]

So, you can use np.concatenate but you have to reshape as well:

>>> final = np.concatenate([arr.reshape(1, 3,3,1) for arr in ax], axis=0)

with a result:

>>> final.shape
(4, 3, 3, 1)
>>> final
array([[[[0],
         [3],
         [1]],

        [[4],
         [2],
         [4]],

        [[2],
         [2],
         [8]]],


       [[[8],
         [4],
         [6]],

        [[7],
         [1],
         [4]],

        [[8],
         [9],
         [8]]],


       [[[6],
         [3],
         [8]],

        [[4],
         [6],
         [8]],

        [[2],
         [2],
         [9]]],


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

        [[0],
         [9],
         [2]],

        [[9],
         [2],
         [3]]]])
>>>

Edit

Inspired by @Divakar to be more generic:

np.concatenate([arr[None,..., None] for arr in ax], axis=0)

Upvotes: 2

Related Questions