Array total comparision


/ Published in: Python
Save to your folder(s)

Compare two arrays wholly. Useful for setting them in regions.


Copy this code and paste it in your HTML
  1. (A==B).all()
  2. test if all values of array (A==B) are True.
  3.  
  4. Edit (from dbaupp's answer and yoavram's comment)
  5.  
  6. It should be noted that:
  7.  
  8. 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.
  9. Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.
  10. In conclusion, the solution I proposed is the standard one, I think, but if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:
  11.  
  12. np.array_equal(A,B) # test if same shape, same elements values
  13. np.array_equiv(A,B) # test if broadcastable shape, same elements values
  14. np.allclose(A,B,...) # test if same shape, elements have close enough values

URL: http://stackoverflow.com/questions/10580676/comparing-two-numpy-arrays-for-equality-element-wise

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.