附加维度 numpy 数组

Append dimensional numpy array

我有两个长度为 32 且形状为 (32, 32, 3) 的 numpy 数组矩阵 A 和 B。我想将它们组合成一个新数组,以便我的新数组的维度为 (2, 32, 32,3).

使用 np.连接引发错误。

使用np.stack

def dim0_stack(*arrays):
    return np.stack(arrays, axis = 0)

另一种方法:

a = np.random.randn(32, 32, 3)
b = np.random.randn(32, 32, 3)
c = np.concatenate([np.expand_dims(a,0), np.expand_dims(b, 0)], axis=0)
print(c.shape)

因为你提到使用 concatenate,我想向你展示如何使用它。

另一种更文字化的方法

result = np.zeros((2, A.shape[0], A.shape[1], A.shape[2]))
result[0, :, :, :] = A
result[1, :, :, :] = B