Search code examples
pythonloopsnumpymatrixindices

Numpy Select indices with complex conditions


Simple question... I hope...

I've got a matrix, a , of size (n x m)

a = np.matrix([[1,2,3],[3,2,1],[6,4,1]])

and I'd like to extract a bool matrix, b, of size (n x m) for the following condition;

b = 3 < a > 7 and a != 6

However it is throwing the following error.

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Any help with this because I'm quite stuck.

Cheers!


Solution

  • You can't use and with arrays as you're trying to compare a single value with an array you have to use &, also you need to enclose the conditions in parentheses due to operator precedence:

    In [56]:
    
    a[(a > 3 ) & (a < 7) & (a != 6)]
    Out[56]:
    matrix([[4]])