如何将 3D NumPy 数组重塑为 2D 数组,同时利用沿轴 2 的数据进行升级? 例如形状为 [2,2,4] 的 3D 数组:
array_3d = [[[ 1 2 3 4]
[ 5 6 7 8]]
[[ 9 10 11 12]
[13 14 15 16]]]
重塑为形状为 [4, 4] 的二维数组:
reshaped_array = [[ 1 2 5 6]
[ 3 4 7 8]
[ 9 10 13 14]
[11 12 15 16]]
我尝试过这种方法:
reshaped_array = array_3d.swapaxes(1, 2).reshape(-1, array_3d.shape[1])
但是我得到了:
[[ 1 5]
[ 2 6]
[ 3 7]
[ 4 8]
[ 9 13]
[10 14]
[11 15]
[12 16]]
假设这个输入:
array = np.arange(1, 17).reshape(2,2,4)
array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8]],
[[ 9, 10, 11, 12],
[13, 14, 15, 16]]])
swapaxes
,然后返回 3D:
array.reshape(2, 2, -1, 2).swapaxes(-2, -3).reshape(2, 2, -1)
array([[[ 1, 2, 5, 6],
[ 3, 4, 7, 8]],
[[ 9, 10, 13, 14],
[11, 12, 15, 16]]])