Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 811
Albert Lázaro de Lara Avatar asked Oct 17 '16 20:10

Albert Lázaro de Lara


People also ask

How do you check if all values in an array are equal Numpy?

The numpy. array_equiv() function can also be used to check whether two arrays are equal or not in Python. The numpy. array_equiv() function returns True if both arrays have the same shape and all the elements are equal, and returns False otherwise.

How do you check if all numbers in an array are equal Python?

You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.

How do you check if a number is in a Numpy array?

Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True” and “False“.


3 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()
like image 195
Eric Avatar answered Oct 19 '22 12:10

Eric


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

np.all(np.isclose(numbers, numbers[0]))
like image 26
crypdick Avatar answered Oct 19 '22 12:10

crypdick


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

like image 29
T_T Avatar answered Oct 19 '22 11:10

T_T