floflo29 floflo29 - 4 months ago 16
Python Question

Test the equality of multiple arguments with Numpy

I would like to test the equality of multiple args (i.e. it should return

True
if all args are equal and
False
if at least one argument differs).

As
numpy.equal
can only handle two arguments, I would have tried reduce but it, obviously, fails:

reduce(np.equal, (4, 4, 4)) # return False because...
reduce(np.equal, (True, 4)) # ... is False

Answer

You can use np.unique to check if the length of unique items within your array is 1:

np.unique(array).size == 1

Or np.all() in order to check if all of the items are equal with one of your items (for example the first one):

np.all(array == array[0])

Demo:

>>> a = np.array([1, 1, 1, 1])
>>> b = np.array([1, 1, 1, 2])

>>> np.unique(a).size == 1
True
>>> np.unique(b).size == 1
False
>>> np.all(a==a[0])
True
>>> np.all(b==b[0])
False
Comments