【问题标题】:how to initialize fixed-size integer numpy arrays in Cython?如何在 Cython 中初始化固定大小的整数 numpy 数组?
【发布时间】:2013-04-16 03:27:10
【问题描述】:

如何在 Cython 中创建 int 类型的空 numpy 数组?以下适用于双数组或浮点数组:

# make array of size N of type float
cdef np.ndarray[float, ndim=1] myarr = np.empty(N)
# make array of size N of type int
cdef np.ndarray[int, ndim=1] myarr = np.empty(N)

但是,如果我尝试对 int 做同样的事情,它会失败:

# this fails
cdef np.ndarray[np.int, ndim=1] myarr = np.empty(N)
# wanted to set first element to be an int
myarr[0] = 5

它给出了错误:

ValueError: 缓冲区 dtype 不匹配,预期为 'int' 但得到了 'double'

因为显然np.empty() 返回一个双精度值。我试过了:

cdef np.ndarray[np.int, ndim=1] myarr = np.empty(N, dtype=int)

但它给出了同样的错误。如何做到这一点?

【问题讨论】:

    标签: python optimization numpy cython


    【解决方案1】:

    包括声明

    cimport numpy as np
    

    并将数组声明为np.int32_t:

    cdef np.ndarray[np.int32_t, ndim=1] myarr = np.empty(N, dtype=np.int32)
    

    您可以从类型声明中删除32,然后使用

    cdef np.ndarray[np.int_t, ndim=1] myarr = np.empty(N, dtype=np.int)
    

    但我更愿意明确说明 numpy 数组中元素的大小。

    请注意,我还将 dtype 添加到 empty; empty 的默认 dtype 是 np.float64

    【讨论】:

    • 为什么这不适用于普通的int 或只是np.int 而不是np.int32_t
    • ndarray 声明的类型参数需要是 C 类型,而不是 Python 对象类型。如果您深入研究 numpy cython 头文件 numpy.pxd,您会发现 np.int32_t 最终导致声明 signed int
    • 您能否解释一下为什么在调用np.empty 时使用dtype=np.int 而不是dtype=np.int32_t?后者不起作用
    【解决方案2】:

    奇怪!我尝试时遇到了同样的错误。但是,查看错误消息,我只是将数组创建的范围更改为一个函数,并且它可以编译!我不知道发生这种情况的原因,但是。

    import numpy as np
    cimport numpy as np
    
    ctypedef np.int_t DTYPE_t
    DTYPE=np.int
    
    def new_array():
        cdef int length = 10
        cdef np.ndarray[DTYPE_t, ndim=1] x = np.zeros([length], dtype=np.int)
        return x
    
    x = new_array()
    

    我认为http://docs.cython.org/src/userguide/language_basics.html#python-functions-vs-c-functions 有一些与 python/c/mixed 变量的作用域相关的信息。

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2011-09-02
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多