Python numpy.nan和逻辑函数:错误的结果

luc*_*one 6 python boolean numpy nan python-2.7

当尝试对可能包含nan值(如numpy中定义)的数据求逻辑表达式时,我得到一些令人惊讶的结果。

我想了解为什么会出现这种结果以及如何实施正确的方法。

我不明白的是为什么这些表达式求值的价值:

from numpy import nan

nan and True
>>> True
# this is wrong.. I would expect to evaluate to nan

True and nan
>>> nan
# OK

nan and False
>>> False
# OK regardless the value of the first element 
# the expression should evaluate to False

False and nan
>>> False
#ok
Run Code Online (Sandbox Code Playgroud)

同样适用于or

True or nan
>>> True #OK

nan or True
>>> nan #wrong the expression is True

False or nan
>>> nan #OK

nan or False
>>> nan #OK
Run Code Online (Sandbox Code Playgroud)

如何实现(有效方式)正确的布尔函数,同时处理nan值?

ev-*_*-br 5

您可以使用numpy命名空间中的谓词:

>>> np.logical_and(True, np.nan), np.logical_and(False, np.nan)
(True, False)
>>> np.logical_and(np.nan, True), np.logical_and(np.nan, False)
(True, False)
>>>
>>> np.logical_or(True, np.nan), np.logical_or(False, np.nan)
(True, True)
>>> np.logical_or(np.nan, True), np.logical_or(np.nan, False)
(True, True)
Run Code Online (Sandbox Code Playgroud)

编辑:内置布尔运算符略有不同。从文档: x and y相当于if x is false, then x, else y. 因此,如果第一个参数的计算结果为False,它们将返回它(不是它的布尔值,就像它一样)。所以:

>>> (None and True) is None
True
>>> [] and True
[]
>>> [] and False
[]
>>> 
Run Code Online (Sandbox Code Playgroud)

等等

  • `np.bool(np.nan)` 评估为 `True`。从那时起,一切都是一致的。 (3认同)