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?
Let's measure the performance by using the following piece of code.
Output
According to the results above, the numpy methods seem to be faster than the combination of the == operator and the all() method and by comparing the numpy methods the fastest one seems to be the numpy.array_equal method.
The
(A==B).all()
solution is very neat, but there are some built-in functions for this task. Namelyarray_equal
,allclose
andarray_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.)test if all values of array (A==B) are True.
Edit (from dbaupp's answer and yoavram's comment)
It should be noted that:
A
orB
is empty and the other one contains a single element, then it returnTrue
. For some reason, the comparisonA==B
returns an empty array, for which theall
operator returnsTrue
.A
andB
don't have the same shape and aren't broadcastable, then this approach will raise an error.In conclusion, the solution I proposed is the standard one, I think, but if you have a doubt about
A
andB
shape or simply want to be safe: use one of the specialized functions:If you want to check if two arrays have the same
shape
ANDelements
you should usenp.array_equal
as it is the method recommended in the documentation.So pretty much equal, no need to talk about the speed.
The
(A==B).all()
behaves pretty much as the following code snippet: