gpt4 book ai didi

python - 将 3D Numpy 数组 reshape 为 2D 数组

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:05 24 4
gpt4 key购买 nike

我在 Numpy 中有以下 3D 数组:

a = np.array([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]],[[13,14],[15,16]]])

当我写作时

b = np.reshape(a, [4,4])

二维结果数组看起来像

 [[ 1  2  3  4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

但是,我希望它是这样的形状:

 [[ 1  2  5  6]
[ 3 4 7 8]
[ 9 10 13 14]
[11 12 15 16]]

我怎样才能在 Python/Numpy 中有效地做到这一点?

最佳答案

reshape 以将第一个轴分成两个,置换轴和另一个 reshape -

a.reshape(2,2,2,2).transpose(0,2,1,3).reshape(4,4)
a.reshape(2,2,2,2).swapaxes(1,2).reshape(4,4)

使其通用化,将成为 -

m,n,r = a.shape
out = a.reshape(m//2,2,n,r).swapaxes(1,2).reshape(-1,2*r)

sample 运行-

In [20]: a
Out[20]:
array([[[ 1, 2],
[ 3, 4]],

[[ 5, 6],
[ 7, 8]],

[[ 9, 10],
[11, 12]],

[[13, 14],
[15, 16]]])

In [21]: a.reshape(2,2,2,2).swapaxes(1,2).reshape(4,4)
Out[21]:
array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])

关于python - 将 3D Numpy 数组 reshape 为 2D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com