I have a 3D numpy
array and I want to add a 2D np array of 0’s to the front of it.
JavaScript
x
20
20
1
import numpy as np
2
A = np.zeros(3,3,3)
3
for i in np.arange(0,2):
4
for j in np.arange(0,2):
5
for k in np.arange(0,2):
6
A[i,j,k] = 10
7
print(A)
8
#returns:
9
[[[10. 10. 0.]
10
[10. 10. 0.]
11
[ 0. 0. 0.]]
12
13
[[10. 10. 0.]
14
[10. 10. 0.]
15
[ 0. 0. 0.]]
16
17
[[ 0. 0. 0.]
18
[ 0. 0. 0.]
19
[ 0. 0. 0.]]]
20
I want to add another array B so that:
JavaScript
1
25
25
1
B = np.zeros(3,3)
2
print(B)
3
#returns
4
[[0. 0. 0.]
5
[0. 0. 0.]
6
[0. 0. 0.]]
7
8
# add B to front of A
9
# B + A =
10
[[[0. 0. 0.]
11
[0. 0. 0.]
12
[0. 0. 0.]]
13
14
[[10. 10. 0.]
15
[10. 10. 0.]
16
[ 0. 0. 0.]]
17
18
[[10. 10. 0.]
19
[10. 10. 0.]
20
[ 0. 0. 0.]]
21
22
[[ 0. 0. 0.]
23
[ 0. 0. 0.]
24
[ 0. 0. 0.]]]
25
I’ve tried np.append(B,A) but it returns a 2D array.
Advertisement
Answer
You can do it using numpy.vstack
and by reshaping your array. For instance:
JavaScript
1
6
1
import numpy as np
2
3
a = np.ones((3, 3, 3))
4
b = np.zeros((3, 3))
5
res = np.vstack((b.reshape(1, 3, 3), a))
6
By the way, you can create your array A
more efficiently:
JavaScript
1
5
1
import numpy as np
2
3
A = np.zeros((3,3,3))
4
A[:2, :2, :2] = 10
5