2

I have an array: [1, 2, 3, 4, 5, 6]. I would like to use the numpy.reshape() function so that I end up with this array:

[[1, 4],
 [2, 5],
 [3, 6]
]

I'm not sure how to do this. I keep ending up with this, which is not what I want:

[[1, 2],
 [3, 4],
 [5, 6]
]
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Rohan
  • 132
  • 4
  • 21

3 Answers3

4

These do the same thing:

In [57]: np.reshape([1,2,3,4,5,6], (3,2), order='F')                                           
Out[57]: 
array([[1, 4],
       [2, 5],
       [3, 6]])
In [58]: np.reshape([1,2,3,4,5,6], (2,3)).T                                                    
Out[58]: 
array([[1, 4],
       [2, 5],
       [3, 6]])

Normally values are 'read' across the rows in Python/numpy. This is call row-major or 'C' order. Read down is 'F', for FORTRAN, and is common in MATLAB, which has Fortran roots.

If you take the 'F' order, make a new copy and string it out, you'll get a different order:

In [59]: np.reshape([1,2,3,4,5,6], (3,2), order='F').copy().ravel()                            
Out[59]: array([1, 4, 2, 5, 3, 6])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
3

You can set the order in np.reshape, in your case you can use 'F'. See docs for details

>>> arr
array([1, 2, 3, 4, 5, 6])

>>> arr.reshape(-1, 2, order = 'F')
array([[1, 4],
       [2, 5],
       [3, 6]])
sacuL
  • 49,704
  • 8
  • 81
  • 106
2

The reason that you are getting that particular result is that arrays are normally allocates in C order. That means that reshaping by itself is not sufficient. You have to tell numpy to change the order of the axes when it steps along the array. Any number of operations will allow you to do that:

  • Set the axis order to F. F is for Fortran, which, like MATLAB, conventionally uses column-major order:

    a.reshape(2, 3, order='F')
    
  • Swap the axes after reshaping:

    np.swapaxes(a.reshape(2, 3), 0, 1)
    
  • Transpose the result:

    a.reshape(2, 3).T
    
  • Roll the second axis forward:

    np.rollaxis(a.reshape(2, 3), 1)
    

Notice that all but the first case require you to reshape to the transpose.

You can even manually arrange the data

np.stack((a[:3], a[3:]), axis=1)

Note that this will make many unnecessary copies. If you want the data copied, just do

a.reshape(2, 3, order='F').copy()
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264