Comparing multiple numpy arrays

how do i compare more than 2 numpy arrays?

import numpy a = numpy.zeros((512,512,3),dtype=numpy.uint8) b = numpy.zeros((512,512,3),dtype=numpy.uint8) c = numpy.zeros((512,512,3),dtype=numpy.uint8) if (a==b==c).all(): pass 

this gives an Error value, and I'm not interested in comparing arrays two at a time.

+5
source share
2 answers

For three arrays, you can check the equality between the corresponding elements between the first and second arrays and then the second and third arrays to give us two Boolean scalars and finally see if both of these scalars are True for the final scalar output, like this -

 np.logical_and( (a==b).all(), (b==c).all() ) 

For more arrays, you can stack them, get differentiation along the stacking axis and check if all these differentiations correspond to zeros. If they are, we have equality among all input arrays, otherwise not. The implementation will look like this:

 L = [a,b,c] # List of input arrays out = (np.diff(np.vstack(L).reshape(len(L),-1),axis=0)==0).all() 
+4
source

For three arrays, you should simply compare them two at a time:

 if np.array_equal(a, b) and np.array_equal(b, c): do_whatever() 

For a variable number of arrays, let all of them be combined into one large arrays array. Then you could do

 if np.all(arrays[:-1] == arrays[1:]): do_whatever() 
+3
source

All Articles