我在尝试评估时得到了一些令人惊讶的结果
可能包含 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
对于 或
类似:
True or nan
>>> True #OK
nan or True
>>> nan #wrong the expression is True
False or nan
>>> nan #OK
nan or False
>>> nan #OK
我如何(以有效的方式)实现正确的 boolean 函数,同时处理 nan
值?
最佳答案
您可以使用 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)
编辑:内置 boolean 运算符略有不同。 From the docs :
x 和 y
等同于 if x is false, then x, else y
。因此,如果第一个参数的计算结果为 False
,它们将返回它(不是它的 boolean 等价物,实际上)。因此:
>>> (None and True) is None
True
>>> [] and True
[]
>>> [] and False
[]
>>>
等等
关于Python numpy.nan 和逻辑函数 : wrong results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17273312/