Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?

前端 未结 3 568
悲哀的现实
悲哀的现实 2021-01-22 19:43

Let\'s say I want to implement Numpy\'s

x[:] += 1

in Cython. I could write

@cython.boundscheck(False)
@cython.wraparoundcheck(F         


        
3条回答
  •  花落未央
    2021-01-22 20:16

    With numpy.ravel

    numpy.ravel(a, order='C')

    Return a contiguous flattened array.

    A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

    @cython.boundscheck(False)
    @cython.wraparound(False)
    def add1_ravel(np.ndarray xs):
        cdef unsigned long i
        cdef double[::1] aview
    
        narray = xs.ravel()
        aview = narray
    
        for i in range(aview.shape[0]):
            aview[i] += 1
    
        # return xs if the memory is shared
        if not narray.flags['OWNDATA'] or np.may_share_memory(xs, narray):
            return xs
    
        # otherwise new array reshaped
        shape = tuple(xs.shape[i] for i in range(xs.ndim))
        return narray.reshape(shape)
    

提交回复
热议问题