Numba:如何获取包含至少一个NaN值的所有行的索引?

huangapple go评论68阅读模式
英文:

Numba: how to get indexes for all rows that contain at least one nan values?

问题

以下是翻译好的部分:

"Suppose I have a numpy 2d array (m by n), I want to get indexes of all its rows contain at least one nan values.

It is relatively straightforward to do it in pure numpy as follows:

import numpy as np

X = np.array([[1, 2], [3, np.nan], [6, 9]])

has_nan_idx = np.isnan(X).any(axis=1)

has_nan_idx
>>> array([False, True, False])

How can I achieve the same using numba njit? For me, I got an error since numba does not support any with arguments.

Thanks."

英文:

Suppose I have a numpy 2d array (m by n), I want to get indexes of all its rows contain at least one nan values.

It is relatively straightforward to do it in pure numpy as follows:

import numpy as np

X = np.array([[1, 2], [3, np.nan], [6, 9]])

has_nan_idx = np.isnan(X).any(axis=1)

has_nan_idx
>>> array([False, True, False])

How can I achieve the same using numba njit? For me, I got an error since numba does not support any with arguments.

Thanks.

答案1

得分: 1

如果您使用 guvectorize,您将自动获得ufunc的好处,例如具有axis关键字的功能。

例如:

from numba import guvectorize

@guvectorize(["void(float64[:], boolean[:])"], "(n)->()")
def isnan_with_axis(x, out):
    
    n = x.size
    out[0] = False
    
    for i in range(n):
        if np.isnan(x[i]):
            out[0] = True
            break

isnan_with_axis(X, axis=1)
# array([False,  True, False])
英文:

If you use guvectorize you'll automatically get the ufunc benefits of having things like the axis keyword.

For example:

from numba import guvectorize

@guvectorize(["void(float64[:], boolean[:])"], "(n)->()")
def isnan_with_axis(x, out):
    
    n = x.size
    out[0] = False
    
    for i in range(n):
        if np.isnan(x[i]):
            out[0] = True
            break

isnan_with_axis(X, axis=1)
# array([False,  True, False])

huangapple
  • 本文由 发表于 2023年2月27日 05:44:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定