【发布时间】: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