How does numpy.reshape() with order = 'F' work? How does numpy.reshape() with order = 'F' work? numpy numpy

How does numpy.reshape() with order = 'F' work?


The elements of a in order 'F'

array([[ 0,  1,  2,  3],       [ 4,  5,  6,  7],       [ 8,  9, 10, 11],       [12, 13, 14, 15]])

are [0,4,8,12,1,5,9 ...]

Now rearrange them in a (2,8) array.

I think the reshape docs talks about raveling the elements, and then reshaping them. Evidently the ravel is done first.

Experiment with a.ravel(order='F').reshape(2,8).

Oops, I get what you expected:

In [208]: a = np.arange(16).reshape(4,4)In [209]: aOut[209]: array([[ 0,  1,  2,  3],       [ 4,  5,  6,  7],       [ 8,  9, 10, 11],       [12, 13, 14, 15]])In [210]: a.ravel(order='F')Out[210]: array([ 0,  4,  8, 12,  1,  5,  9, 13,  2,  6, 10, 14,  3,  7, 11, 15])In [211]: _.reshape(2,8)Out[211]: array([[ 0,  4,  8, 12,  1,  5,  9, 13],       [ 2,  6, 10, 14,  3,  7, 11, 15]])

OK, I have to keep the 'F' order during the reshape

In [214]: a.ravel(order='F').reshape(2,8, order='F')Out[214]: array([[ 0,  8,  1,  9,  2, 10,  3, 11],       [ 4, 12,  5, 13,  6, 14,  7, 15]])In [215]: a.ravel(order='F').reshape(2,8).flagsOut[215]:   C_CONTIGUOUS : True  F_CONTIGUOUS : False  ...In [216]: a.ravel(order='F').reshape(2,8, order='F').flagsOut[216]:   C_CONTIGUOUS : False  F_CONTIGUOUS : True

From np.reshape docs

You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.

The notes on order are fairly long, so it's not surprising that the topic is confusing.