所以我要说我有一个像这样的数组:
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
]
我试图将每2个数组堆叠在一起,所以我最终得到以下结果:
[
[[1, 2, 3], [1, 2, 3]],
[[1, 2, 3], [1, 2, 3]],
]
特别重要的是要尽可能高效,因为这将在不太强大的硬件上运行,所以我宁愿这样做而不需要循环遍历数组。有没有办法在不使用循环的情况下在numpy中实现它。
解决办法:
如果您的第一个维度是偶数(2的倍数),您可以使用reshape将2-D数组转换为3-D数组,如下所示。这里唯一的事情是将第一个维度拆分为一半(除以2)并将其转换为整数,因为形状参数必须是整数
arr_old = np.array([
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
])
x, y = arr_old.shape # The shape of this input array is (4, 3)
arr_new = arr_old.reshape(int(x/2), int(x/2), y) # Reshape the old array
print (arr_new.shape)
# (2, 2, 3)
print (arr_new)
# [[[1 2 3]
# [1 2 3]]
# [[1 2 3]
# [1 2 3]]]








暂无数据