使用python/numpy重塑数组 [英] reshape an array using python/numpy

查看:139
本文介绍了使用python/numpy重塑数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重塑以下数组:

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

我尝试了不同的组合,但没有用.

I have tried different combinations but none works.

谢谢

推荐答案

具有重塑和转置/交换轴的方法-

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)

样品运行-

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

这篇关于使用python/numpy重塑数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆