6

I have the following array:

x = np.arange(24).reshape((2,3,2,2))
array([[[[ 0,  1],
     [ 2,  3]],

    [[ 4,  5],
     [ 6,  7]],

    [[ 8,  9],
     [10, 11]]],


   [[[12, 13],
     [14, 15]],

    [[16, 17],
     [18, 19]],

    [[20, 21],
     [22, 23]]]])

I would like to reshape it to a (3,4,2) array like below:

array([[[ 0,  1],
    [ 2,  3],
    [12, 13],
    [14, 15]],

   [[ 4,  5],
    [ 6,  7],
    [16, 17],
    [18, 19]],

   [[ 8,  9],
    [10, 11],
    [20, 21],
    [22, 23]]])

I've tried to use reshape but it gave me the following which is not what I want.

array([[[ 0,  1],
    [ 2,  3],
    [ 4,  5],
    [ 6,  7]],

   [[ 8,  9],
    [10, 11],
    [12, 13],
    [14, 15]],

   [[16, 17],
    [18, 19],
    [20, 21],
    [22, 23]]])

Can someone please help?

Allen Qin
  • 19,507
  • 8
  • 51
  • 67

3 Answers3

8

Use transpose and then reshape like so -

shp = x.shape
out = x.transpose(1,0,2,3).reshape(shp[1],-1,shp[-1])
Divakar
  • 218,885
  • 19
  • 262
  • 358
1
x = np.arange(24).reshape((2,3,2,2))
y = np.dstack(zip(x))[0]
print y

result:

[[[ 0  1]
  [ 2  3]
  [12 13]
  [14 15]]

 [[ 4  5]
  [ 6  7]
  [16 17]
  [18 19]]

 [[ 8  9]
  [10 11]
  [20 21]
  [22 23]]]
Julien
  • 13,986
  • 5
  • 29
  • 53
  • 1
    Thanks Julien. This works fine. However, I'm more after a native numpy solution for performance reasons. – Allen Qin Aug 13 '16 at 05:49
  • 1
    This function is going to be used to transform large numpy arrays many times. I'm not sure if zip is optimized for these kind of array operations. – Allen Qin Aug 13 '16 at 05:55
  • 1
    Nothing wrong with both yours and Divakar's solution. I just spent a bit time testing the performance of both solution. It turned out Divakar's solution is twice faster so I marked his solution as the answer. Thank you both. – Allen Qin Aug 13 '16 at 06:40
1

You can also use concatenate like so-

out=np.concatenate((x),axis=1)

I will note those since you mentioned this is for performance, this doesn't seem faster than Divakar suggestion:

shp = x.shape
out = x.transpose(1,0,2,3).reshape(shp[1],-1,shp[-1])

If anyone does a bench mark or finds something faster I would love to know.

Supamee
  • 615
  • 5
  • 15