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

前端 未结 3 1990
孤街浪徒
孤街浪徒 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 19:50

    To force a numpy array x to be C-contiguous, without making unnecessary copies when it's already that way to begin with, you should use,

     x = numpy.asarray(x, order='C')
    

    Note, that if this array was not C-contiguous, it would probably be similar in terms of efficiency to x.copy(order='C'). I don't think there is a way around it. You can't reorganize the alignment of an array in memory otherwise than by making a copy of the data to a new location.

    Rewriting your code so it uses the sliced index first, as in numpy.ones((5,1024,1024)) seems to be the only reasonable way of optimizing this.

提交回复
热议问题