Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two NumPy arrays for equality, element-wise

What is the simplest way to compare two NumPy arrays for equality (where equality is defined as: A = B iff for all indices i: A[i] == B[i])?

Simply using == gives me a boolean array:

 >>> numpy.array([1,1,1]) == numpy.array([1,1,1])  array([ True,  True,  True], dtype=bool) 

Do I have to and the elements of this array to determine if the arrays are equal, or is there a simpler way to compare?

like image 501
clstaudt Avatar asked May 14 '12 09:05

clstaudt


People also ask

How do you compare two NumPy arrays are equal?

To check if two NumPy arrays A and B are equal: Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.

How do you check if all elements in an array are equal NumPy?

The numpy. array_equiv() function can also be used to check whether two arrays are equal or not in Python. The numpy. array_equiv() function returns True if both arrays have the same shape and all the elements are equal, and returns False otherwise.

How do I check if two arrays are identical in Python?

Compare Two Arrays in Python Using the numpy. array_equiv() Method. The numpy. array_equiv(a1, a2) method takes array a1 and a2 as input and returns True if both arrays' shape and elements are the same; otherwise, returns False .


2 Answers

(A==B).all() 

test if all values of array (A==B) are True.

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

Special cases and alternatives (from dbaupp's answer and yoavram's comment)

It should be noted that:

  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values np.array_equiv(A,B)  # test if broadcastable shape, same elements values np.allclose(A,B,...) # test if same shape, elements have close enough values 
like image 84
Juh_ Avatar answered Sep 19 '22 21:09

Juh_


The (A==B).all() solution is very neat, but there are some built-in functions for this task. Namely array_equal, allclose and array_equiv.

(Although, some quick testing with timeit seems to indicate that the (A==B).all() method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)

like image 27
huon Avatar answered Sep 19 '22 21:09

huon