我有一個(gè) 3Dnumpy數(shù)組,我想在它的前面添加一個(gè) 0 的 2D np 數(shù)組。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.]]]我想添加另一個(gè)數(shù)組 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) 但它返回一個(gè)二維數(shù)組。
1 回答

ibeautiful
TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用numpy.vstack并通過重塑您的陣列來做到這一點(diǎn)。例如:
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更有效地創(chuàng)建數(shù)組:
import numpy as np
A = np.zeros((3,3,3))
A[:2, :2, :2] = 10
添加回答
舉報(bào)
0/150
提交
取消