30

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?

5 Answers 5

49

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()
Sign up to request clarification or add additional context in comments.

2 Comments

or use the builtin: all(numbers==0)
@bebop: Which is slower
26

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

np.all(np.isclose(numbers, numbers[0]))

Comments

4

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

1 Comment

This fails with non-numerical dtype's
-3

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

3 Comments

This is good but it unnecessarily creates a copy of the array.
Incorrect: for e.g. [1, 0] it should be False since 1 != 0, but [1, 0] == [1, 0]. To be precise, this is a roundabout way of evaluating a == a, which is true iff a does not contain a nan
I don't see it as a solution
-6

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()

1 Comment

I highly doubt that creating a hashtable of the array and looking up and inserting each element of a numpy array, that have to be fetched individually through the whole numpy + python call stack) is going to be faster than creating a boolean mask in numpy, and short circuited all-checking of that array also completely in numpy. Some timeit or plots of the scaling of your solution compared to numpy might be in order. len(set(numbers)) doesn't short circuit at all, it needs to hash and compare each value to the existing set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.