Cheapest way to get a numpy array into C-contiguous order?

前端 未结 3 1988
孤街浪徒
孤街浪徒 2021-01-01 19:09

The following produces a C-contiguous numpy array:

import numpy

a = numpy.ones((1024,1024,5))

Now if I slice it, the result may not longer

3条回答
  •  遥遥无期
    2021-01-01 20:12

    This is a standard operation when interfacing numpy with C. Have a look at numpy.ascontiguousarray

    x=numpy.ascontiguousarray(x)

    is the proper way of dealing with it.

    Use numpy.asfortranarray if you need fortran order.

    As mentioned the function will copy if necessary. So there is no way around it. You can try rollaxis before your operation, such that the short axis is the first axis. This gives you a view on the array

    In [2]: A=np.random.rand(1024,1024,5)
    In [3]: B=np.rollaxis(A,2)
    In [4]: B.shape
    Out[4]: (5, 1024, 1024)
    In [5]: B.flags
    Out[5]:
      C_CONTIGUOUS : False
      F_CONTIGUOUS : False
      OWNDATA : False
      WRITEABLE : True
      ALIGNED : True
      UPDATEIFCOPY : False
    
    In [6]: A.flags
    Out[6]:
      C_CONTIGUOUS : True
      F_CONTIGUOUS : False
      OWNDATA : True
      WRITEABLE : True
      ALIGNED : True
      UPDATEIFCOPY : False
    

    So rollaxis does not solve this either.

提交回复
热议问题