蟒蛇numpy.nan和逻辑功能:错误的结果 [英] Python numpy.nan and logical functions: wrong results

查看:203
本文介绍了蟒蛇numpy.nan和逻辑功能:错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图评估时,我得到了一些令人惊讶的结果
在可能包含值(如numpy的定义)的数据逻辑前pressions。

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.

我不明白的是为什么这些前pressions评估为他们做的值:

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

我如何能实现(以有效的方式)正确的布尔函数,也处理值?

推荐答案

您可以使用predicates从 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)

编辑:内置的布尔运算稍有不同。 <一href=\"http://docs.python.org/2/library/stdtypes.html?highlight=short%20circuit#boolean-operations-and-or-not\"相对=nofollow>从文档:
x和y 等同于如果x是假的,那么x,否则是。所以,如果第一个参数的计算结果为,他们返回它(的的布尔及其等价物,因为它是)。因此:

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
[]
>>> 

这篇关于蟒蛇numpy.nan和逻辑功能:错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆