Combining logic statements AND in numpy array

arrays, numpy, python

Solution

you could just use `&`, eg:

x = np.arange(10)
(x<8) & (x>2)

gives

array([False, False, False,  True,  True,  True,  True,  True, False, False], dtype=bool)

A few details:

- This works because `&` is shorthand for the numpy ufunc `bitwise_and`, which for the `bool` type is the same as `logical_and`. That is, this could also be spelled out as `bitwise_and(less(x,8), greater(x,2))`

- You need the parentheses because in numpy `&` has higher precedence than `<` and `>`

- `and` does not work because it is ambiguous for numpy arrays, so rather than guess, numpy raise the exception.

Problem

What would be the way to select elements when two conditions are `True` in a matrix? In R, it is basically possible to combine vectors of booleans. So what I'm aiming for: ``` A = np.array([2,2,2,2,2]) A < 3 and A > 1 # A < 3 & A > 1 does not work either ``` Evals to: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() It should eval to: ``` array([True,True,True,True,True]) ``` My workaround usually is to sum these boolean vectors and equate to 2, but there must be a better way. What is it?

Original source