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

Since Numba 0.19, you can explicitly create numpy arrays in nopython mode. How to create an array of a certain type?

from numba import jit
import numpy as np

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

The above code does not work with the following error

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

You should use numbadtypes insteadnumpy

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)
+4
source

In python 2.7, np.int seems to work.

Regarding the workaround from dlenz, I would like to point out that using np.int32 really works ... with the added benefit that the code will work unchanged if you want to remove numba.njit at some point for some reason .

+1
source

All Articles