Let's start with 2 2D arrays:
import numpy as np
a = np.zeros( (3,4) )
b = np.zeros( (3,4) )
Now let's combine them into a 3D array:
c = np.stack( (a,b) )
Everything fine so far, but how to add an additional 2D array to the 3D array, the following is not working:
np.stack( (c,a) )
So, my question is how to add an additional layer to the 3D array? (numpy version 1.12.1
)
If you know all of your 2D arrays at the start, you can just stack 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 "stacked" array and want to add another array to it, you can use e.g. numpy.concatenate
:
If the array you want to add is "flat", you would have to wrap it in a list to make the dimensions match. By default, the arrays are joined along the first dimension (same as if you were to specify axis=0
in the keyword arguments):
>>> c.shape
(2, 3, 4)
>>> np.array([a]).shape
(1, 3, 4)
c = np.concatenate((c, [a]))
If both arrays are already "stacked", this will also work:
c = np.concatenate((c, c))
You can add a new axis with None/np.newaxis
at the start of the array to be appended : a[None,:,:]
or simply a[None,...]
or just a[None]
and for stacking use np.vstack
.
Here's a sample run to make things clear -
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
So, the workflow would be :
1) To start off with 2D
arrays, use new axes for the arrays :
c = np.vstack( (a[None],b[None]) )
2) For later appending steps, use new axis for the incoming 2D
array and use np.vstack
to stack with the existing 3D
array -
d = np.vstack((c,a[None]))
Using np.concatenate
for performance :
np.vstack
under the hoods uses np.concatenate
as a special case when we need to stack along the first axis. So, if we want to make use of np.concatenate
maybe for performance reasons to avoid the additional function call overhead, we need to specify the axis of concatenation, which would be the first axis.
Thus, with 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With