I have a 3D matrix:
array = np.array([[[1,2,3,4,5],[4,5,6,1,3], [7,8,9,6,7],[1,2,3,5,5],[4,5,6,8,9], [7,8,9,4,7]],[[1,2,3,4,5],[4,5,6,1,3], [7,8,9,6,7],[1,2,3,5,5],[4,5,6,8,9], [7,8,9,4,7]]])
This results the matrix as:
array([[[1, 2, 3, 4, 5],
[4, 5, 6, 1, 3],
[7, 8, 9, 6, 7],
[1, 2, 3, 5, 5],
[4, 5, 6, 8, 9],
[7, 8, 9, 4, 7]],
[[1, 2, 3, 4, 5],
[4, 5, 6, 1, 3],
[7, 8, 9, 6, 7],
[1, 2, 3, 5, 5],
[4, 5, 6, 8, 9],
[7, 8, 9, 4, 7]]])
Now, I want to add a zero vector or matrix created using
x = np.zeros((1,5))
with the matrix array such that the result becomes:
array([[[1, 2, 3, 4, 5],
[4, 5, 6, 1, 3],
[7, 8, 9, 6, 7],
[1, 2, 3, 5, 5],
[4, 5, 6, 8, 9],
[7, 8, 9, 4, 7],
[0, 0, 0, 0, 0]],
[[1, 2, 3, 4, 5],
[4, 5, 6, 1, 3],
[7, 8, 9, 6, 7],
[1, 2, 3, 5, 5],
[4, 5, 6, 8, 9],
[7, 8, 9, 4, 7],
[0, 0, 0, 0, 0]]])
Can anyone help? I tried with concatenation and stacks, including dstack but they didn't work (or I could not properly implement). I tried
a = np.vstack((array[0], x))
b = np.vstack((array[1], x))
then I tried to join them as the 3D array using dstack as:
np.dstack((a, b))
this didn't work.
Direct concatenation (np.concatenate(array,x)) of course cannot work. That is why I tried to make a 3D zeros array but maybe np.zeros only create 2D arrays (or 1D given one dimension is 1)
Let's say arr
is your (2, 6, 5)
shaped array.
First make a suitably shaped array of zeros:
zeros = np.zeros((2, 1, 5))
This array has a 5-element row of zeros for each 'page' of your 3-D array.
Then use concatenate
(since you want to join along an existing axis):
np.concatenate((arr, zeros), axis=1)
Result:
array([[[1., 2., 3., 4., 5.],
[4., 5., 6., 1., 3.],
[7., 8., 9., 6., 7.],
[1., 2., 3., 5., 5.],
[4., 5., 6., 8., 9.],
[7., 8., 9., 4., 7.],
[0., 0., 0., 0., 0.]],
[[1., 2., 3., 4., 5.],
[4., 5., 6., 1., 3.],
[7., 8., 9., 6., 7.],
[1., 2., 3., 5., 5.],
[4., 5., 6., 8., 9.],
[7., 8., 9., 4., 7.],
[0., 0., 0., 0., 0.]]])
You can use np.append
for this and then merge two 3d arrays using np.concatenate
ie
a = np.array([[[1,2,3,4,5],[4,5,6,1,3], [7,8,9,6,7],[1,2,3,5,5],[4,5,6,8,9], [7,8,9,4,7]],[[1,2,3,4,5],[4,5,6,1,3], [7,8,9,6,7],[1,2,3,5,5],[4,5,6,8,9], [7,8,9,4,7]]])
z = np.zeros((1,5), dtype=int)
new = np.append(a[0], z, axis=0)
new1 = np.append(a[1], z, axis=0)
new2 = np.concatenate(([new], [new1]))
print(new2)
Output;
[[[1 2 3 4 5]
[4 5 6 1 3]
[7 8 9 6 7]
[1 2 3 5 5]
[4 5 6 8 9]
[7 8 9 4 7]
[0 0 0 0 0]]
[[1 2 3 4 5]
[4 5 6 1 3]
[7 8 9 6 7]
[1 2 3 5 5]
[4 5 6 8 9]
[7 8 9 4 7]
[0 0 0 0 0]]]
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.