如何重塑()numpy中的奇数行和偶数行之和

时间:2018-07-04 07:28:24

标签: python python-3.x numpy reshape

示例1:

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

我想要reshape()2D数组并组合奇数行和偶数行。

所需结果

[[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 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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