简体   繁体   中英

Stack several 2D arrays to produce a 3D array

I have 4 numpy arrays, each of shape (5,5). I would like to stack them such that I get a new array of shape (5,5,4). I tried using:

N = np.stack((a, b, c, d))

but, as I am new to using numpy, I cannot understand why that is giving a shape of (4, 5, 5) instead of (5, 5, 4). Is there another method I should be using? dstack works but changes my arrays, I think it transposes them.

For example, 4 arrays

[[1,2]
 [3,4]]

[[1,2]
 [3,4]]

[[1,2]
 [3,4]]

[[1,2]
 [3,4]]

when stacked I am expecting:

[[[1,2]
 [3,4]]

[[1,2]
 [3,4]]

[[1,2]
 [3,4]]

[[1,2]
 [3,4]]]

This is working as expected with stack but would give a shape of (4,2,2) instead of (2,2,4). From my understanding, shape is (rows, columns, depth) Am I wrong in this?

I believe you could concatenate the arrays, and reshape into a 3D array as:

l = [a,b,c,d]
np.concatenate(l).reshape(len(l), *a.shape)

Or if you want to avoid creating that list and know the amount of arrays beforehand:

np.concatenate((a,b,c,d)).reshape(4, *a.shape)

Checking on the shared example:

a = [[1, 2], [3, 4]]
d = c = b = a

np.concatenate((a,b,c,d)).reshape(4, *np.array(a).shape)
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])
In [10]: arr = np.arange(1,5).reshape(2,2)
In [11]: np.stack((arr,arr,arr))
Out[11]: 
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])
In [12]: _.shape
Out[12]: (3, 2, 2)

Default stack joins the arrays on a new first axis, the same as np.array((arr,arr,arr)).shape

If given an axis parameter it can join them as:

In [13]: np.stack((arr,arr,arr), axis=2)
Out[13]: 
array([[[1, 1, 1],
        [2, 2, 2]],

       [[3, 3, 3],
        [4, 4, 4]]])
In [14]: _.shape
Out[14]: (2, 2, 3)

np.dstack does the same thing, where d stands for 'depth`'.

The last dimension (here 3) is displayed as the innermost columns.

Selecting one 'channel' produces a 2d array:

In [17]: np.stack((arr,arr,arr), axis=2)[:,:,0]
Out[17]: 
array([[1, 2],
       [3, 4]])

For 3 dimensions, the first dimension is blocks or planes, and the middle rows. Those names are conveniences, helping us visualize the action, but don't have inherent means in numpy . For images the last dimension often is called colors or channels, and has size 3 or 4. A 4d array of images could described as

(batches, height, width, color)

But the actual meanings depend on how you are processing the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM