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

标签 python python-3.x 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 数据类型而不是 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 - 如何使用 numba 创建给定类型的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31266046/

相关文章:

python - 如何在分配之前将变量评估为另一个变量?

python-3.x - jupyter 实验室中的 Bqplot 返回字符串而不是(交互式)图像

python - 如何使用 numba 优化 numpy.packbits?

python - 将 numpy.fill 与 Numba 'nopython' 模式结合使用

python - 有没有办法缩短多个条件,如下所示?

Python super() 传入 *args

python - 如何将 3D vtkDataSet 转换为 numpy 数组?

json - folium.GeoJson(样式函数)无法按我想要的方式工作

python - ModuleNotFoundError : No module named 'tf_slim' despite installing

python-3.x - 在类里面使用 numba?