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?
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.
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.
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“.
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()
If you want to compare floats, use np.isclose
instead:
np.all(np.isclose(numbers, numbers[0]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With