首页 文章

在Cython中使用类型化的内存视图返回numpy友好数组的正确方法?

提问于
浏览
6

我试图使用Cython内存视图而不创建或采用numpy数组,所以我永远不必编译numpy,但我'd like to return things that on the Python side can be '强制转换为numpy数组 . 例如,我有这个函数,它接受一个2D数组并返回一个新的1d数组:

cimport cython
from cython.view cimport array as cvarray

cpdef int[:] myfunc(int[:,:] input_arr, int arr_len):
   cdef int i
   # allocate new int array
   cdef int[:] new_arr = cvarray(shape=(arr_len,), itemsize=sizeof(int), format="i") 
   for i in xrange(arr_len):
      if input_arr[i, 0] == 1:
         new_arr[i] = 0
      else:
         new_arr[i] = 1
   return new_arr

现在从Python我实际上想要将一个numpy数组传递给该函数并将结果视为一个numpy数组:

# From Python
import numpy as np
data = np.array([[0,0,0],[1,0,1]], dtype=np.dtype("i"))
result = myfunc(data, data.shape[0])
# How do I make 'result' accessible as numpy array here??
# ...
result = np.array(result)  # one possibility

怎么办?我的方式是否正确?更具体的问题:

  • 引用 new_arr[x] 会回到Python吗?我希望它是数组的纯C索引

  • cdef int[:] new_arr = ...cdef int[::1] new_arr = ... 之间有区别吗?我不明白后者

  • cvarray 这是在这里分配内存的最佳方式,还是 clone ?使用numpy数组我会使用 np.empty ,我试图在这里获得有效的东西 . 另外,为什么在 cvarray 调用中需要 format="i" .

  • Finally ,如果 clone 是正确的语法,它如何用于2d数组? https://github.com/cython/cython/blob/f94ad59754a0f0b1cef4a334b988a21392a738c0/Cython/Includes/cpython/array.pxd目前还不清楚

这与这篇文章(What is the recommended way of allocating memory for a typed memory view?)有关,我对此并不完全了解 .

1 回答

  • 4

    除非你需要在Cython中的其他地方使用这个函数,否则你应该使用 def 而不是 cpdef . 要返回 numpy 数组,可以使用 np.asarray() ,如下所示:

    import numpy as np
    cimport cython
    from cython.view cimport array as cvarray
    
    def myfunc(int[:,:] input_arr, int arr_len):
       cdef int i
       # allocate new int array
       cdef int[:] new_arr = cvarray(shape=(arr_len,), itemsize=sizeof(int), format="i") 
       for i in xrange(arr_len):
          if input_arr[i, 0] == 1:
             new_arr[i] = 0
          else:
             new_arr[i] = 1
       return np.asarray(new_arr)
    

相关问题