Comparing two NumPy arrays for equality, element-wise
(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
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
. - Another risk is if
A
andB
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 valuesnp.array_equiv(A,B) # test if broadcastable shape, same elements valuesnp.allclose(A,B,...) # test if same shape, elements have close enough values
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.)
If you want to check if two arrays have the same shape
AND elements
you should use np.array_equal
as it is the method recommended in the documentation.
Performance-wise don't expect that any equality check will beat another, as there is not much room to optimize
comparing two elements
. Just for the sake, i still did some tests.
import numpy as npimport timeitA = np.zeros((300, 300, 3))B = np.zeros((300, 300, 3))C = np.ones((300, 300, 3))timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)> 51.5094> 52.555> 52.761
So pretty much equal, no need to talk about the speed.
The (A==B).all()
behaves pretty much as the following code snippet:
x = [1,2,3]y = [1,2,3]print all([x[i]==y[i] for i in range(len(x))])> True