Numpy: You Need to Understand What Happens to the "In" Statement

I would appreciate it if someone would help me with this (and explain what is happening).

It works:

>>> from numpy import array >>> a = array((2, 1)) >>> b = array((3, 3)) >>> l = [a, b] >>> a in l True 

But this is not so:

 >>> c = array((2, 1)) >>> c in l Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

The behavior I would like to reproduce is as follows:

 >>> x = (2, 1) >>> y = (3, 3) >>> l2 = [x, y] >>> z = (2, 1) >>> z in l2 True 

Note that the above also works with mutable objects:

 >>> x = [2, 1] >>> y = [3, 3] >>> l2 = [x, y] >>> z = [2, 1] >>> z in l2 True 

Of course, knowing that:

 >>> (a < b).all() True 

I tried (and could not):

 >>> (c in l).all() Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 
+6
source share
1 answer

Python makes the choice that bool([False,True]) be True because (it says) any non-empy list has a boolean value of True.

Numpy makes the choice that bool(np.array([False, True])) should raise a ValueError. Numpy was designed in terms of the fact that some users may want to know if any elements in the array are True, while others may want to find out if all elements are in the array True. Since users may have conflicting desires, NumPy refuses to guess. It raises a ValueError and suggests using np.any or np.all (although if you want to replicate behavior like Python, use len ).

When you evaluate c in l , Python compares c with every element in l , starting with a . It evaluates bool(c==a) . We get a bool(np.array([True True])) that raises a ValueError (for the reason described above).

Since numpy refuses to guess, you have to be specific. I suggest:

 import numpy as np a=np.array((2,1)) b=np.array((3,3)) c=np.array((2,1)) l=[a,b] print(any(np.all(c==elt) for elt in l)) # True 
+6
source

Source: https://habr.com/ru/post/900663/


All Articles