重塑一个 numpy 数组,使列环绕在原始行之下

问题描述 投票:0回答:2

考虑以下场景:

a = np.array([[1,1,1,3,3,3], [2,2,2,4,4,4]])
np.reshape(a, (4, 3))

输出:

array([[1, 1, 1],
       [3, 3, 3],
       [2, 2, 2],
       [4, 4, 4]])

期望的输出:

array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4]])

我如何重塑数组,使行保持成对在一起,并且溢出的列环绕在现有行下方?

python numpy reshape
2个回答
2
投票

正如我在评论中描述的那样。您可以将其合并为一个声明:

import numpy as np
a = np.array([[1,1,1,3,3,3], [2,2,2,4,4,4]])

a1 = a[:,:3]
a2 = a[:,3:]
a3 = np.concatenate((a1,a2))
print(a3)

输出:

[[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]]

0
投票

还有一个选择:

import numpy as np

a = np.hstack(a.T.reshape(2,3,2)).T

print(a)

输出

array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4]])
© www.soinside.com 2019 - 2024. All rights reserved.