Issue
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?
Solution
(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 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
Answered By - Juh_
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.