使用Python/Numpy重新塑造数组

3
我想重构以下数组:
>>> test
array([ 11.,  12.,  13.,  14.,  21.,  22.,  23.,  24.,  31.,  32.,  33.,
        34.,  41.,  42.,  43.,  44.])

为了获得:
>>> test2
array([[ 11.,  12.,  21.,  22.],
       [ 13.,  14.,  23.,  24.],
       [ 31.,  32.,  41.,  42.],
       [ 33.,  34.,  43.,  44.]])

我曾尝试使用"reshape"来处理类似的事情

>>> test.reshape(4,4)
    array([[ 11.,  12.,  13.,  14.],
           [ 21.,  22.,  23.,  24.],
           [ 31.,  32.,  33.,  34.],
           [ 41.,  42.,  43.,  44.]]) 

同时

 >>> test.reshape(2,2,2,2)
     array([[[[ 11.,  12.],
              [ 13.,  14.]],

              [[ 25.,  26.],
              [ 27.,  28.]]],


              [[[ 39.,  31.],
              [ 32.,  33.]],

              [[ 41.,  44.],
              [ 45.,  46.]]]])

我尝试过不同的组合,但都没有成功。
谢谢。
1个回答

5

通过重塑和转置/交换轴来处理 -

m,n = 2,2  # Block size (rowxcol)
rowlen = 4 # Length of row
out = test.reshape(-1,m,rowlen//n,n).swapaxes(1,2).reshape(-1,rowlen)
# Or transpose(0,2,1,3)

样例运行 -

In [104]: test
Out[104]: 
array([ 11.,  12.,  13.,  14.,  21.,  22.,  23.,  24.,  31.,  32.,  33.,
        34.,  41.,  42.,  43.,  44.])

In [105]: m,n = 2,2  # Block size (rowxcol)
     ...: rowlen = 4 # Length of row
     ...: 

In [106]: test.reshape(-1,m,rowlen//n,n).swapaxes(1,2).reshape(-1,rowlen)
Out[106]: 
array([[ 11.,  12.,  21.,  22.],
       [ 13.,  14.,  23.,  24.],
       [ 31.,  32.,  41.,  42.],
       [ 33.,  34.,  43.,  44.]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接