Why does inserting a new axis make the data non-contiguous?
>>> a = np.arange(12).reshape(3,4,order='F')
>>> a
array([[ 0, 3, 6, 9],
[ 1, 4, 7, 10],
[ 2, 5, 8, 11]])
>>> a.reshape((3,1,4)).flags
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> a[np.newaxis,...].flags
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> a.flags
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
Note that if I use C
ordering, it does maintain contiguous data when I reshape, but not when I add a new axis:
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> a.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> a.reshape(3,1,4).flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> a[np.newaxis,...].flags
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
update For those who might find this in a search, to keep the current array order in a reshape, a.reshape(3,1,4,order='A')
works and keeps a contiguous array contiguous.
For those asking "why do you care?", This is part of a script which is passing the arrays in fortran order to some fortran subroutines compiled via f2py
. The fortran routines require 3D data so I'm padding the arrays with new dimensions to get them up to the required number of dimensions. I'd like to keep contiguous data to avoid copy-in/copy-out behavior.
This doesn't answer your question but may be of some use:
You can also make use of numpy.require
np.require(a[np.newaxis,...], requirements='FA').flags
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With