Creating a 3D array from a series of numpy 2D arrays

Let's start with 2 2D arrays:

import numpy as np
a = np.zeros( (3,4) )
b = np.zeros( (3,4) )

Now merge them into a three-dimensional array:

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

Everything is still fine, but how to add an additional 2D array to the 3D array, the following does not work:

np.stack( (c,a) )

So my question is how to add an extra layer to a 3D array? (numpy version 1.12.1)

+4
source share
3 answers

If you know all of your 2D arrays at the beginning, you can simply add more than two of them:

import numpy as np
a = np.zeros((3, 4))
b = np.zeros((3, 4))
c = np.stack((a, b, a))

If you already have one “complex” array and you want to add another array to it, you can use, for example numpy.concatenate:

, , "", , . ( , axis=0 ):

>>> c.shape
(2, 3, 4)
>>> np.array([a]).shape
(1, 3, 4)

c = np.concatenate((c, [a]))

"", :

c = np.concatenate((c, c))
+4

None/np.newaxis : a[None,:,:] a[None,...] a[None], np.vstack.

, -

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

In [15]: d = np.vstack((c,a[None]))

In [16]: d.shape
Out[16]: (3, 3, 4)

In [17]: e = np.vstack((d,a[None]))

In [18]: e.shape
Out[18]: (4, 3, 4)

Workflow

, :

1) 2D, :

c = np.vstack( (a[None],b[None]) )

2) 2D np.vstack 3D -

d = np.vstack((c,a[None]))

np.concatenate :

np.vstack np.concatenate , . , np.concatenate, , , , , .

, np.concatenate -

In [23]: d = np.concatenate((c, a[None]), axis=0)

In [24]: d.shape
Out[24]: (3, 3, 4)

In [25]: e = np.concatenate((d, a[None]), axis=0)

In [26]: e.shape
Out[26]: (4, 3, 4)
+2

First take the same measurement as c result= np.append(c, [a], axis=0)
But it is inefficient to resize numpy arrays, unlike lists

+1
source

Source: https://habr.com/ru/post/1674636/


All Articles