如何在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 回答
包括声明
并将数组声明为
np.int32_t
:您可以从类型声明中删除
32
,然后使用但我更喜欢明确numpy数组中元素的大小 .
请注意,我还将dtype添加到
empty
;empty
的默认dtype是np.float64
.Wierd!我尝试的时候遇到了同样的错误 . 但是,查看错误消息,我只是将数组创建的范围更改为函数,然后编译!我不知道为什么会这样,但是 .
我认为http://docs.cython.org/src/userguide/language_basics.html#python-functions-vs-c-functions有一些与python / c / mixed变量的范围有关的信息 .