1

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?

Gihun Joo
  • 57
  • 4
  • Your **desired result** is inconsistent with your actual *desire* (provided that by "rows" you mean the 0-th index of the array). It looks more like you want to combine the 1-st index odd and even "columns" (or rather row-column combinations)? Is that right? – a_guest Jul 04 '18 at 07:35
  • Can you add a sample with more number of rows, just to avoid confusion? – Divakar Jul 04 '18 at 07:38
  • It looks like the result should involve odd and even rows *after* performing `a.reshape(-1, 3)`. That's basically also what the OP says, "first reshape then combine odd and even rows". – a_guest Jul 04 '18 at 07:42

2 Answers2

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]])
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Your answer happens to be correct for `a.shape[1] == 2` but for any other size of the 2nd dimension it won't. Take for example `a = np.arange(36).reshape(4, 3, 3)`. You will have as many rows as the 2nd dim's size but the OP wants odd and even, i.e. exactly 2. – a_guest Jul 04 '18 at 07:46
  • @a_guest Yeah, that's why my comment to the question for clarification, because I don't think OP meant odd, even rows, but more like permuting axes. I will wait for the clarification. – Divakar Jul 04 '18 at 07:47
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]])
Sunitha
  • 11,777
  • 2
  • 20
  • 23