numpy appending a 2D array to a 3D array
Question:
i’d appreciate guidance on appending a 2D zeros array to a 3D array. so as to add multiple layers to a 2×2 matrix.
#so,
n = np.zeros((1,3,3,), np.ubyte)
n[0][0][1] = n[0][1][0] = 1
#return prints:
[[[0, 1, 0],
[1, 0, 0],
[0, 0, 0]]]
then how do you add another 2D array of zero elements to, in pseudocode:
a = np.zeros((3,3,), np.ubyte)
n = np.append(n, a)
#return prints:
[[[0 1 0]
[1 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]]
and so on with the latter two lines to add any number of layers of the 3×3 2D matrix.
thank you in advance, lucas
Answers:
Generally, the arrays need to have the same shape. To join along an existing axis, you can use np.concatenate
:
np.concatenate([n, a[None,...]], axis=0)
Note, this adds an extra dimension to a
, or equivalently, we can extend along a new axis using np.stack
:
np.stack([n[0], a], axis=0)
Note, in the above case, we removed a dimension from n
.
As noted in the comments though, this is inefficient, this will scale very inefficiently (quadratic time on the total size), so keep that in mind.
Note, bot arr[0]
and arr[None, ...]
are "cheap" operations (constant time) and don’t copy the underlying buffer, they create views.
i’d appreciate guidance on appending a 2D zeros array to a 3D array. so as to add multiple layers to a 2×2 matrix.
#so,
n = np.zeros((1,3,3,), np.ubyte)
n[0][0][1] = n[0][1][0] = 1
#return prints:
[[[0, 1, 0],
[1, 0, 0],
[0, 0, 0]]]
then how do you add another 2D array of zero elements to, in pseudocode:
a = np.zeros((3,3,), np.ubyte)
n = np.append(n, a)
#return prints:
[[[0 1 0]
[1 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]]
and so on with the latter two lines to add any number of layers of the 3×3 2D matrix.
thank you in advance, lucas
Generally, the arrays need to have the same shape. To join along an existing axis, you can use np.concatenate
:
np.concatenate([n, a[None,...]], axis=0)
Note, this adds an extra dimension to a
, or equivalently, we can extend along a new axis using np.stack
:
np.stack([n[0], a], axis=0)
Note, in the above case, we removed a dimension from n
.
As noted in the comments though, this is inefficient, this will scale very inefficiently (quadratic time on the total size), so keep that in mind.
Note, bot arr[0]
and arr[None, ...]
are "cheap" operations (constant time) and don’t copy the underlying buffer, they create views.