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

Python numpy.nan and logical functions: wrong results(Python numpy.nan 和逻辑函数:错误的结果)
本文介绍了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 和逻辑函数:错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)