Home > Back-end >  How to check if all values of an array are equal to each other?
How to check if all values of an array are equal to each other?

Time:10-22

I want to check if an array has all the same value in it. An example would be as follows.

array1 = np.array([1,1,1,1,1]) would return True
array2 = np.array([1,0,1,0,1]) would return False

I know how to check if all values in an array are equal to a certain value. But I want to check if all values in the array are equal to each other, no matter what the value is. Is there a way to do this with just Numpy without creating a function?

CodePudding user response:

You can use python sets. If the length of the set is 1, all values are the same:

>>> len(set(array1)) == 1
True

>>> len(set(array2)) == 1
False

CodePudding user response:

This works too and seems to be slightly faster than some other approaches:

>>> array1 = np.array([1,1,1,1,1])
>>> array2 = np.array([1,0,1,0,1])
>>> (array1 == array1[0]).all()
True
>>> (array2 == array2[0]).all()
False

Some very coarse timing figures for a 10k array, compared to other solutions:

  • this approach: 1.07 msec
  • np.isin(): 1.23 msec
  • set(): 2.63 msec

CodePudding user response:

This can be used- np.unique

import numpy as np

array1 = np.array([1,1,1,1,1])
#following passes assertion test
assert(len(np.unique(array1, return_counts=True)[0])==1)

#without getting counts of unique values
#assert(len(np.unique(array1))==1)

array2 = np.array([1,0,1,0,1])
#following will throw an assertion error
assert(len(np.unique(array2, return_counts=True)[0])==1)

CodePudding user response:

My attempt would be to compare all items to the first item and then check if the result contains a False:

import numpy as np
array1 = np.array([1,1,1,1,1])
print(not np.isin(False, array1 == array1[0]))

On my machine, this becomes faster than the len(set()) version at about 700 numbers in the array. At 10000 items, it's faster by a factor of 5.5. But it's slower than the np.unique() version. Measured on a Core i7-10750H, 10000 iterations

  • Related