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

前端 未结 3 1980
孤街浪徒
孤街浪徒 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:11

    As things stand, any attempt to coerce the slice bn to C contiguous order is going to create a copy.

    If you don't want to change the shapes you're starting with (and don't need a itself in C order), one possible solution is to start with the array a in Fortran order:

    >>> a = numpy.ones((1024, 1024, 5), order='f')
    

    The slices are also then F-contiguous:

    >>> bn = a[:, :, 0]
    >>> bn.flags
      C_CONTIGUOUS : False
      F_CONTIGUOUS : True
      OWNDATA : False
      ...
    

    This means that the transpose of the slice bn will be in C order and transposing does not create a copy:

    >>> bn.T.flags
      C_CONTIGUOUS : True
      F_CONTIGUOUS : False
      OWNDATA : False
      ...
    

    And you can then hash the slice:

    >>> hashlib.sha1(bn.T).hexdigest()
    '01dfa447dafe16b9a2972ce05c79410e6a96840e'
    

提交回复
热议问题