numpy数组上的算术比较 [英] arithmetic comparisons on numpy arrays
问题描述
>>> import numpy as np
>>> x = np.eye(3)
>>> x[1, 2] = .5
>>> x
array([[ 1. , 0. , 0. ],
[ 0. , 1. , 0.5],
[ 0. , 0. , 1. ]])
>>> 0 < x.any() < 1
False
>>>
我想检查numpy数组是否包含0到1之间的任何值.
我将0 < x.any() < 1
读为如果有任何大小大于0且小于1的元素,则返回true",但是显然不是这种情况.
I would like to check if numpy array contains any value between 0 and 1.
I read 0 < x.any() < 1
as 'if there is any element with size greater then 0 and less then 1, return true', but that's obviously not the case.
如何在numpy数组上进行算术比较?
How can I do arithmetic comparison on numpy array?
推荐答案
>>> np.any((0 < x) & (x < 1))
True
x.any()
实际执行的操作:与np.any(x)
相同,这意味着如果x
中的任何元素都不为零,则返回True
.因此,您的比较结果是0 < True < 1
,这是错误的,因为在python 2中,0 < True
是true,但由于True == 1
,True < 1
不是.
What x.any()
actually does: it's the same as np.any(x)
, meaning it returns True
if any elements in x
are nonzero. So your comparison is 0 < True < 1
, which is false because in python 2 0 < True
is true, but True < 1
is not, since True == 1
.
相反,在这种方法中,我们对每个元素进行比较是否为真的布尔数组,然后检查该数组中是否有任何元素为真:
In this approach, by contrast, we make boolean arrays of whether the comparison is true for each element, and then check if any element of that array is true:
>>> 0 < x
array([[ True, False, False],
[False, True, True],
[False, False, True]], dtype=bool)
>>> x < 1
array([[False, True, True],
[ True, False, True],
[ True, True, False]], dtype=bool)
>>> (0 < x) & (x < 1)
array([[False, False, False],
[False, False, True],
[False, False, False]], dtype=bool)
您必须执行显式的&
,因为不幸的是numpy不能(而且我认为不能)与python的比较运算符的内置链接一起工作.
You have to do the explicit &
, because unfortunately numpy doesn't (and I think can't) work with python's built-in chaining of comparison operators.
这篇关于numpy数组上的算术比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!