Changing array with fancy indexing?

I have the following functions:

@njit
def switch(arr):
    arr[np.isnan(arr)]= -9999.0
    return arr

@njit
def switchB(arr):
    idxs = np.nonzero(np.isnan(arr))
    arr[idxs]= -9999.0
    return arr

Ran it both with the following array,

a = np.arange(25.0).reshape((5,5))
a[0,4] = np.nan

but get an error. Is there a way to do fancy indexing within an array inside a numba function?

You can use np.nan_to_num. Inplace is probably faster. If you want to return the array set copy to true.

@njit
def switch(arr):
    np.nan_to_num(arr, copy=False, nan=-9999.0)
1 Like