如何切割和扩展2D numpy数组?

the*_*est 5 python numpy

我有一个大小的numpy数组nxm.我想要限制列的数量,k并希望在新行中扩展其余列.以下是情景 -

初始数组: nxm

最终阵列: pxk

哪里 p = (m/k)*n

例如. n = 2, m = 6, k = 2

初始数组:

[[1, 2, 3, 4, 5, 6,],
[7, 8, 9, 10, 11, 12]]
Run Code Online (Sandbox Code Playgroud)

最终阵列:

[[1, 2],
[7, 8],
[3, 4],
[9, 10],
[5, 6],
[11, 12]]
Run Code Online (Sandbox Code Playgroud)

我试过使用reshape但没有得到理想的结果.

gg3*_*349 4

这是一种方法

q=array([[1, 2, 3, 4, 5, 6,],
         [7, 8, 9, 10, 11, 12]])
r=q.T.reshape(-1,2,2)
s=r.swapaxes(1,2)
t=s.reshape(-1,2)
Run Code Online (Sandbox Code Playgroud)

作为一个班轮,

q.T.reshape(-1,2,2).swapaxes(1,2).reshape(-1,2)

array([[ 1,  2],
       [ 7,  8],
       [ 3,  4],
       [ 9, 10],
       [ 5,  6],
       [11, 12]])
Run Code Online (Sandbox Code Playgroud)

编辑:对于一般情况,使用

q=arange(1,1+n*m).reshape(n,m) #example input
r=q.T.reshape(-1,k,n)
s=r.swapaxes(1,2)
t=s.reshape(-1,k)
Run Code Online (Sandbox Code Playgroud)

一个班轮是:

q.T.reshape(-1,k,n).swapaxes(1,2).reshape(-1,k)
Run Code Online (Sandbox Code Playgroud)

例如n=3,m=12,k=4

q=array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12],
         [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
         [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]])
Run Code Online (Sandbox Code Playgroud)

结果是

array([[ 1,  2,  3,  4],
       [13, 14, 15, 16],
       [25, 26, 27, 28],
       [ 5,  6,  7,  8],
       [17, 18, 19, 20],
       [29, 30, 31, 32],
       [ 9, 10, 11, 12],
       [21, 22, 23, 24],
       [33, 34, 35, 36]])
Run Code Online (Sandbox Code Playgroud)