Search code examples
pythonnumpyconditional-statementsand-operator

Using boolean opeation between 2 arrays in python


I have two arrays, lets say:

a = np.array([1,2,3,4,5,6,7])
b = np.array([1,2,10,18,3,4,7])

Now I would like to apply a double condition, 2<a<6 and 2<b<6. Now how can I get those objects of a and b for which 2<a<6 and 2<b<6 ?

I tried

condition_a = a[(a>2)*(a<6)]
condition_b = b[(b>2)*(b<6)]

new_a = a[(condition_a) and (condition_b)]
new_b = b[(condition_a) and (condition_b)]

But it doesn't work!!


Solution

  • mask = (a>2) & (a<6) & (b>2) & (b<6)
    new_a = a[mask]
    new_b = b[mask]
    

    Using & given the same result as *, but since we are performing a logical_and here, I think it is clearer to use &.