numpy:具有多个元素的数组的真值不明确 [英] Numpy : The truth value of an array with more than one element is ambiguous
问题描述
我真的很困惑为什么出现此错误.这是我的代码:
I am really confused on why this error is showing up. Here is my code:
import numpy as np
x = np.array([0, 0])
y = np.array([10, 10])
a = np.array([1, 6])
b = np.array([3, 7])
points = [x, y, a, b]
max_pair = [x, y]
other_pairs = [p for p in points if p not in max_pair]
>>>ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
(a not in max_paix)
>>>ValueError: The truth ...
让我感到困惑的是,以下方法工作正常:
What confuses me is that the following works fine:
points = [[1, 2], [3, 4], [5, 7]]
max_pair = [[1, 2], [5, 6]]
other_pairs = [p for p in points if p not in max_pair]
>>>[[3, 4], [5, 7]]
([5, 6] not in max_pair)
>>>False
为什么在使用numpy数组时会发生这种情况? not in/in
是否存在歧义?
any()\all()
的正确语法是什么?
Why is this happening when using numpy arrays? Is not in/in
ambiguous for existance?
What is the correct syntax using any()\all()
?
推荐答案
Numpy数组定义了一个自定义的相等运算符,即它们是实现__eq__
魔术函数的对象.因此,==
运算符和所有依赖于这种相等性的其他函数/运算符都称为此自定义相等性函数.
Numpy arrays define a custom equality operator, i.e. they are objects that implement the __eq__
magic function. Accordingly, the ==
operator and all other functions/operators that rely on such an equality call this custom equality function.
Numpy的相等性基于数组的逐元素比较.因此,作为回报,您将获得另一个具有布尔值的numpy数组.例如:
Numpy's equality is based on element-wise comparison of arrays. Thus, in return you get another numpy array with boolean values. For instance:
x = np.array([1,2,3])
y = np.array([1,4,5])
x == y
返回
array([ True, False, False], dtype=bool)
但是,将in
运算符与 lists 结合使用时,要求相等比较仅返回单个布尔值.这就是错误要求all
或any
的原因.例如:
However, the in
operator in combination with lists requires equality comparisons that only return a single boolean value. This is the reason why the error asks for all
or any
. For instance:
any(x==y)
返回True
,因为结果数组的至少一个值为True
.
相反
returns True
because at least one value of the resulting array is True
.
In contrast
all(x==y)
返回False
,因为不是结果数组的所有值都是True
.
returns False
because not all values of the resulting array are True
.
因此,在您的情况下,解决该问题的方法如下:
So in your case, a way around the problem would be the following:
other_pairs = [p for p in points if all(any(p!=q) for q in max_pair)]
和print other_pairs
打印预期结果
[array([1, 6]), array([3, 7])]
为什么呢?好吧,我们从 points 中寻找一个 p 项,其中任何项与 all 项不相等 max_pair 中的项目 q .
Why so? Well, we look for an item p from points where any of its entries are unequal to the entries of all items q from max_pair.
这篇关于numpy:具有多个元素的数组的真值不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!