In [327]: x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])
In [329]: x.reshape(3,3)
Out[329]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [330]: x.reshape(3,3).base
Out[330]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
In [331]: x.reshape(3,3).T.base
Out[331]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
The reshape and transpose return view
, so are relatively fast. It's the reshape after the transpose that makes a copy.
We can specify an order when reshaping:
In [332]: x.reshape(3,3,order='F')
Out[332]:
array([[0, 3, 6],
[1, 4, 7],
[2, 5, 8]])
But again the reshape after makes a copy:
In [333]: x.reshape(3,3,order='F').ravel()
Out[333]: array([0, 3, 6, 1, 4, 7, 2, 5, 8])
Actually if we specify the same order, the ravel is a view:
In [334]: x.reshape(3,3,order='F').ravel(order='F')
Out[334]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
But the default order of reshape/ravel
is 'C':
In [335]: x.reshape(3,3,order='F').ravel(order='C')
Out[335]: array([0, 3, 6, 1, 4, 7, 2, 5, 8])
Regardless of how we do it, reordering the elements as in [335] requires a copy; it can't be a view.