简体   繁体   English

使用python / numpy重塑数组

[英]reshape an array using python/numpy

I want to reshape the following array: 我想重塑以下数组:

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

in order to obtain: 为了获得:

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

I have tried with "reshape" something like 我尝试过“重塑”之类的东西

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

And

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

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


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

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

I have tried different combinations but none works. 我尝试过不同的组合但没有效果。

Thanks 谢谢

Approach with reshaping and transposing/swapping axes - 重塑和转置/交换轴的方法 -

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)

Sample run - 样品运行 -

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.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM