包含 NaN 的两个条件的布尔索引

Boolean indexing with two conditions to include NaN

我想在 numpy 数组和 pandas 系列上使用布尔索引,以 select 在特定列中具有

import numpy as np

a = [0.5, 0, 1, 17, np.nan]
b = np.array(a)
c = b[b < 3 or b == np.nan]

其中一个应该可以解决问题:

c = b[np.logical_or(b < 3, b == np.nan)]
# or
c = b[np.where((b < 3) | (b == np.nan))]
# or
c = b[(b < 3) | (b == np.nan)]

我不知道一个比另一个有什么好处,但如果我不得不猜测,我会说 np.where 一个可能稍微快一点?只是猜测。

您需要使用括号,将 or 替换为 | 运算符并使用 np.isnan 而不是 ==

c = b[(b < 3) | np.isnan(b)]

RuntimeWarning 可能是因为它试图将 NaN 值与数字进行比较。您可以尝试在该会话中忽略它:

with np.errstate(invalid='ignore'):
    c = b[(b < 3) | np.isnan(b)]