Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy using the reshape function to reshape an array [duplicate]

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]
]
like image 375
Rohan Avatar asked Jun 15 '26 16:06

Rohan


2 Answers

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])
like image 66
hpaulj Avatar answered Jun 18 '26 05:06

hpaulj


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]])
like image 21
sacuL Avatar answered Jun 18 '26 04:06

sacuL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!