且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 a.any() 或 a.all()

更新时间:2022-10-15 08:45:18

如果你看一下 valeur 的结果,你就会明白是什么导致了这种歧义:

>>>价值

所以结果是另一个数组,在这种情况下有 4 个布尔值.现在结果应该是什么?当一个值为真时,条件是否应该为真?只有当所有值都为真时,条件才应该为真吗?

这正是 numpy.anynumpy.all 所做的.前者要求至少有一个真值,后者要求所有值都为真:

>>>np.any(价值

x = np.arange(0,2,0.5)
valeur = 2*x

if valeur <= 0.6:
    print ("this works")
else:   
    print ("valeur is too high")

here is the error I get:

if valeur <= 0.6:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have read several posts about a.any() or a.all() but still can't find a way that really clearly explain how to fix the problem. I see why Python does not like what I wrote but I am not sure how to fix it.

If you take a look at the result of valeur <= 0.6, you can see what’s causing this ambiguity:

>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)

So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?

That’s exactly what numpy.any and numpy.all do. The former requires at least one true value, the latter requires that all values are true:

>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False