What are the rules for comparing numpy arrays using ==?

For example, trying to understand these results:

>>> x array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> (x == np.array([[1],[2]])).astype(np.float32) array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32) >>> (x == np.array([1,2])) False >>> (x == np.array([[1]])).astype(np.float32) array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32) >>> (x == np.array([1])).astype(np.float32) array([ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32) >>> (x == np.array([[1,3],[2]])) False >>> 

What's going on here? In the case of [1], it compares 1 with each element x and aggregates the result in an array. In the case of [[1]] the same. It’s easy to understand what will happen for specific array forms by simply experimenting with repl. But what are the basic rules in which both sides can have arbitrary forms?

+5
source share
2 answers

NumPy tries to pass these two arrays to compatible forms before comparing. If the translation fails, False is currently returned. In the future

The equality operator == will cause errors in the future, such as np.equal, if translating or comparing elements, etc. not executed.

Otherwise, a logical array is returned, obtained as a result of comparing elements by element. For example, since x and np.array([1]) are broadcast, an array of form (10) is returned:

 In [49]: np.broadcast(x, np.array([1])).shape Out[49]: (10,) 

Since x and np.array([[1,3],[2]]) not transmitted, False returns x == np.array([[1,3],[2]]) .

 In [50]: np.broadcast(x, np.array([[1,3],[2]])).shape --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-50-56e4868cd7f7> in <module>() ----> 1 np.broadcast(x, np.array([[1,3],[2]])).shape ValueError: shape mismatch: objects cannot be broadcast to a single shape 
+4
source

It is possible that you are confused by the fact that:


 x == np.array([[1],[2]]) 

. It compares x with each of the first and second arrays; since they are scalars, translation implies that it compares each element of x with each of the scalars.


However each of

 x == np.array([1,2]) 

and

 x == np.array([[1,3],[2]]) 

cannot be transferred. For me, with numpy 1.10.4, this gives

 /usr/local/bin/ipython:1: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future. #!/usr/bin/python False 
+3
source

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


All Articles