Numping inserting axis makes data non-contiguous

Why does adding 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 retains continuous data when the shape changes, but not when adding 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 can find this in a search to keep the current array order in change, a.reshape(3,1,4,order='A') works and saves a continuous continuous array.


For those who ask, “Why does it bother you?”, This is the part of the script that passes arrays in fortran order to some fortran routines compiled via f2py . Fortran routines require 3D data, so I populate arrays with new dimensions to get them to the required number of dimensions. I would like to keep adjacent data in order to avoid copy / copy behavior.

+6
source share
1 answer

This does not answer your question, but may be useful: You can also use numpy.require np.require(a[np.newaxis,...], requirements='FA').flags
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False

+1
source

Source: https://habr.com/ru/post/945513/


All Articles