Comparing two NumPy arrays for equality, element-wise Comparing two NumPy arrays for equality, element-wise python python

Comparing two NumPy arrays for equality, element-wise


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 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