Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use numpy.where with logical operators

I'm trying to find the indices of all elements in an array that are greater than a but less than b. It's probably just a problem with my syntax but this doesn't work:

numpy.where((my_array > a) and (my_array < b)) 

How should I fix this? Or is there a better way to do it?

Thanks!

like image 391
ylangylang Avatar asked Nov 27 '12 17:11

ylangylang


People also ask

What is the use of where in NumPy?

The numpy. where() function returns the indices of elements in an input array where the given condition is satisfied. Parameters: condition : When True, yield x, otherwise yield y.

Can you use where in Python?

In Python, we can use the numpy. where() function to select elements from a numpy array, based on a condition. Not only that, but we can perform some operations on those elements if the condition is satisfied.

Where do we use logical operators?

The logical operators are used primarily in the expression evaluation to make a decision. These operators allow the evaluation and manipulation of specific bits within the integer. This operator returns true if all relational statements combined with && are true, else it returns false.

Can NumPy have mixed data types?

Having a data type (dtype) is one of the key features that distinguishes NumPy arrays from lists. In lists, the types of elements can be mixed.


1 Answers

Here are two ways:

In [1]: my_array = arange(10)  In [2]: where((my_array > 3) & (my_array < 7)) Out[2]: (array([4, 5, 6]),)  In [3]: where(logical_and(my_array > 3, my_array < 7)) Out[3]: (array([4, 5, 6]),) 

For the first (replacing and with &), be careful to add parentheses appropriately: & has higher precedence than the comparison operators. You can also use *, but I wouldn't recommend it: it's hacky and doesn't make for readable code.

In [4]: where((my_array > 3) * (my_array < 7)) Out[4]: (array([4, 5, 6]),) 
like image 186
Mark Dickinson Avatar answered Sep 24 '22 06:09

Mark Dickinson