首页 文章

如何在Cython中初始化固定大小的整数numpy数组?

提问于
浏览
8

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

# 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)

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

2 回答

  • 10

    包括声明

    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 .

  • 1

    Wierd!我尝试的时候遇到了同样的错误 . 但是,查看错误消息,我只是将数组创建的范围更改为函数,然后编译!我不知道为什么会这样,但是 .

    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变量的范围有关的信息 .

相关问题