Numpy: how I can determine if all elements of numpy array are equal to a number

Question:

I need to know if all the elements of an array of numpy are equal to a number

It would be like:

numbers = np.zeros(5) # array[0,0,0,0,0]
print numbers.allEqual(0) # return True because all elements are 0

I can make an algorithm but, there is some method implemented in numpy library?

Answers:

You can break that down into np.all(), which takes a boolean array and checks it’s all True, and an equality comparison:

np.all(numbers == 0)
# or equivalently
(numbers == 0).all()
Answered By: Eric

If you want to compare floats, use np.isclose instead:

np.all(np.isclose(numbers, numbers[0]))
Answered By: crypdick

Are numpy methods necessary? If all the elements are equal to a number, then all the elements are the same. You could do the following, which takes advantage of short circuiting.

numbers[0] == 0 and len(set(numbers)) == 1 

This way is faster than using np.all()

Answered By: billiam

np.array_equal() also works (for Python 3).

tmp0 = np.array([0]*5)
tmp1 = np.array([0]*5)

np.array_equal(tmp0, tmp1)

returns True

Answered By: T_T

The following version checks the equality of all entries of the array without requiring the repeating number.

numbers_0 = np.zeros(5) # array[0,0,0,0,0]
numbers.ptp() == 0.0  # True

# checking an array having some random repeating entry
numbers_r = np.ones((10, 10))*np.random.rand()
numbers_r.ptp() == 0.0  # True
Answered By: Rajesh Nakka
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.