Python numpy.nan and logical functions: wrong results(Python numpy.nan 和逻辑函数:错误的结果)
问题描述
我在尝试评估时得到了一些令人惊讶的结果可能包含 nan
值的数据的逻辑表达式(在 numpy 中定义).
I get some surprising results when trying to evaluate
logical expressions on data that might contain nan
values (as defined in numpy).
我想了解为什么会出现这种结果以及如何正确实施.
I would like to understand why this results arise and how to implement the correct way.
我不明白为什么这些表达式的计算结果是它们所做的值:
What I don't understand is why these expressions evaluate to the value they do:
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
如何(以有效的方式)实现正确的布尔函数,同时处理 nan
值?
How can I implement (in an efficient way) the correct boolean functions, handling also nan
values?
推荐答案
您可以使用 numpy
命名空间中的谓词:
You can use predicates from the numpy
namespace:
>>> 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)
内置布尔运算符略有不同.来自文档一个>:x and y
等价于 if x is false, then x, else y
.因此,如果第一个参数的计算结果为 False
,它们将返回它(不是它的布尔等价物,因为它是).因此:
The built-in boolean operators are slightly different. From the docs :
x and y
is equivalent to if x is false, then x, else y
. So, if the first argument evaluates to False
, they return it (not its boolean equivalent, as it were). Therefore:
>>> (None and True) is None
True
>>> [] and True
[]
>>> [] and False
[]
>>>
等
这篇关于Python numpy.nan 和逻辑函数:错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python numpy.nan 和逻辑函数:错误的结果


基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01