Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to test if each element in an numpy array lies between two values?

Tags:

python

numpy

I was wondering if there was a syntactically simple way of checking if each element in a numpy array lies between two numbers.

In other words, just as numpy.array([1,2,3,4,5]) < 5 will return array([True, True, True, True, False]), I was wondering if it was possible to do something akin to this:

1 < numpy.array([1,2,3,4,5]) < 5 

... to obtain ...

array([False, True, True, True, False]) 

I understand that I can obtain this through logical chaining of boolean tests, but I'm working through some rather complex code and I was looking for a syntactically clean solution.

Any tips?

like image 478
Louis Thibault Avatar asked May 10 '12 21:05

Louis Thibault


People also ask

How do I compare values in two Numpy arrays?

To check if two NumPy arrays A and B are equal: Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.

How do you check if an element 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“.

How do you compare two elements in python arrays?

To compare two arrays and return the element-wise minimum, use the numpy. fmin() method in Python Numpy. Return value is either True or False. Compare two arrays and returns a new array containing the element-wise maxima.

How do you check if all elements 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.


2 Answers

One solution would be:

import numpy as np a = np.array([1, 2, 3, 4, 5]) (a > 1) & (a < 5) # array([False,  True,  True,  True, False]) 
like image 180
mata Avatar answered Oct 09 '22 04:10

mata


Another would be to use numpy.any, Here is an example

import numpy as np a = np.array([1,2,3,4,5]) np.any((a < 1)|(a > 5 )) 
like image 37
sushmit Avatar answered Oct 09 '22 04:10

sushmit