Python numpy.nan 和逻辑函数 : wrong results

标签 python python-2.7 numpy boolean nan

我在尝试评估时得到了一些令人惊讶的结果 可能包含 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/

相关文章:

python - 如何从 Python 列表字典中的值生成所有组合

python:如何找到不是子字符串而是子图片?

python - 列表理解嵌套在字典中的列表

python - 从python中的元组中获取具有值的项目

python - 在 ThreadPool 线程之间共享 gevent 锁/信号量?

python - 如何更改Python数组的编码?

python - Flask-paginate 不显示分页按钮

python - 在 Jupyter - Python 中有 2 个 Ipywidgets 作用于一个 matplotlib 图

python - 为数组的索引实现 np.subtract.outer([[array .... python 中的结构

python - ML - 特征选择后获取特征名称 - SelectPercentile,python