【问题标题】:reshape an array using python/numpy使用 python/numpy 重塑数组
【发布时间】:2017-07-22 14:49:18
【问题描述】:

我想重塑以下数组:

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

我尝试过“重塑”类似的东西

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

我尝试了不同的组合,但没有一个有效。

谢谢

【问题讨论】:

    标签: python arrays numpy reshape


    【解决方案1】:

    使用重塑和转置/交换轴的方法 -

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 2019-05-05
      • 2016-02-10
      相关资源
      最近更新 更多