Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Cython中初始化固定大小的整数numpy数组?_Python_Optimization_Numpy_Cython - Fatal编程技术网

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

Python 如何在Cython中初始化固定大小的整数numpy数组?,python,optimization,numpy,cython,Python,Optimization,Numpy,Cython,如何在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

如何在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:缓冲区数据类型不匹配,应为“int”,但为“double”

因为显然
np.empty()
返回一个double。我试过:

cdef np.ndarray[np.int, ndim=1] myarr = np.empty(N, dtype=int)
但它给出了同样的错误。如何做到这一点?

包括该声明

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数组中元素的大小


注意,我还将数据类型添加到
empty
empty
的默认数据类型是
np.float64

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

我认为有一些与python/c/混合变量的作用域相关的信息。

为什么这不适用于普通的
int
或仅仅
np.int
而不是
np.int32\t
?ndarray声明的类型参数需要是c类型,而不是python对象类型。如果您深入研究numpy cython头文件
numpy.pxd
,您会发现
np.int32\u t
最终导致声明
signed int
。您能解释一下为什么在调用
np.empty
时使用
dtype=np.int
而不是
dtype=np.int32\t
吗?后者不起作用