How to reshape () the sum of odd and even rows in numpy

我怕爱的太早我们不能终老 提交于 2019-12-20 03:49:16

问题


Example1 :

a = np.array([[[1,11,111],[2,22,222]],
              [[3,33,333],[4,44,444]],
              [[5,55,555],[6,66,666]],[[7,77,777],[8,88,888]]])

>>> a
array([[[  1,  11, 111],
    [  2,  22, 222]],

   [[  3,  33, 333],
    [  4,  44, 444]],

   [[  5,  55, 555],
    [  6,  66, 666]],

   [[  7,  77, 777],
    [  8,  88, 888]]])

i want reshape() 2D-array and combine odd rows and even rows.

Desired result :

[[1, 11, 111, 3, 33, 333, 5, 55, 555, 7, 77, 777],
 [2, 22, 222, 4, 44, 444, 6, 66, 666, 8, 88, 888]]

How can I make the output like above?


回答1:


Permute axes and reshape to 2D -

In [14]: a
Out[14]: 
array([[[  1,  11, 111],
        [  2,  22, 222]],

       [[  3,  33, 333],
        [  4,  44, 444]],

       [[  5,  55, 555],
        [  6,  66, 666]],

       [[  7,  77, 777],
        [  8,  88, 888]]])

In [15]: a.swapaxes(0,1).reshape(a.shape[1],-1)
Out[15]: 
array([[  1,  11, 111,   3,  33, 333,   5,  55, 555,   7,  77, 777],
       [  2,  22, 222,   4,  44, 444,   6,  66, 666,   8,  88, 888]])



回答2:


>>> np.array(list(zip(*a))).reshape(2,12)
array([[  1,  11, 111,   3,  33, 333,   5,  55, 555,   7,  77, 777],
       [  2,  22, 222,   4,  44, 444,   6,  66, 666,   8,  88, 888]])


来源:https://stackoverflow.com/questions/51168095/how-to-reshape-the-sum-of-odd-and-even-rows-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!