如何使用 numba 创建给定类型的 numpy 数组

How to create a numpy array of a given type with numba

从 Numba 0.19 开始,就可以在 nopython 模式下显式创建 numpy 数组。如何创建给定类型的数组?

from numba import jit
import numpy as np

@jit(nopython=True)
def f():
    a = np.zeros(5, dtype = np.int)

以上代码失败并出现以下错误

TypingError: Failed at nopython (nopython frontend)
Undeclared Function(<built-in function zeros>)(int32, Function(<class 'int'>))
File "<ipython-input-4-3169be7a8201>", line 6

你应该使用 numba dtypes 而不是 numpy

import numba
import numpy as np

@numba.njit
def f():
    a = np.zeros(5, dtype=numba.int32)
    return a

In [8]: f()
Out[8]: array([0, 0, 0, 0, 0], dtype=int32)

在 python 2.7 中似乎 np.int 确实有效。

至于 dlenz 的变通方法,我想指出的是使用 np.int32 也能正常工作...还有一个额外的好处,如果您想删除 numba.njit 在某些时候出于某种原因。