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!
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.
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.
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.
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.
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]),)
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