我有一个 3Dnumpy数组,我想在它的前面添加一个 0 的 2D np 数组。import numpy as npA = np.zeros(3,3,3)for i in np.arange(0,2): for j in np.arange(0,2): for k in np.arange(0,2): A[i,j,k] = 10print(A)#returns: [[[10. 10. 0.] [10. 10. 0.] [ 0. 0. 0.]] [[10. 10. 0.] [10. 10. 0.] [ 0. 0. 0.]] [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]]]我想添加另一个数组 B 以便:B = np.zeros(3,3)print(B)#returns [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]# add B to front of A # B + A = [[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] [[10. 10. 0.] [10. 10. 0.] [ 0. 0. 0.]] [[10. 10. 0.] [10. 10. 0.] [ 0. 0. 0.]] [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]]]我试过 np.append(B,A) 但它返回一个二维数组。
1 回答
ibeautiful
TA贡献1993条经验 获得超5个赞
您可以使用numpy.vstack并通过重塑您的阵列来做到这一点。例如:
import numpy as np
a = np.ones((3, 3, 3))
b = np.zeros((3, 3))
res = np.vstack((b.reshape(1, 3, 3), a))
顺便说一句,您可以A更有效地创建数组:
import numpy as np
A = np.zeros((3,3,3))
A[:2, :2, :2] = 10
添加回答
举报
0/150
提交
取消