Srivatsan
Srivatsan

Reputation: 9363

Python, opposite of conditional array

I have two numpy arrays, let's say A and B

In [3]: import numpy as np

In [4]: A = np.array([0.10,0.20,0.30,0.40,0.50])

In [5]: B = np.array([0.15,0.23,0.33,0.41,0.57])

I apply a condition like this:

In [6]: condition_array = A[(B>0.2)*(B<0.5)]

In [7]: condition_array
Out[7]: array([ 0.2,  0.3,  0.4])

Now how do I get the opposite of condition_array?

i.e. the values of array A for which array B is NOT GREATER THAN 0.2 and NOT LESS THAN 0.5 ?

In [8]: test_array = A[(B<0.2)*(B>0.5)]

In [9]: test_array
Out[9]: array([], dtype=float64)

The above doesn't seem to work !

Upvotes: 1

Views: 416

Answers (2)

piRSquared
piRSquared

Reputation: 294488

By De Morgan's Law

A[np.logical_or(~(B > 0.2), ~(B < 0.5)]

Or

A[np.logical_or(B <= 0.2, B >= 0.5)]

Upvotes: 1

mgilson
mgilson

Reputation: 310049

You can use the ~ operator to invert the array ...

A[~((B>0.2)*(B<0.5))]

Note that your use of * seems like it's meant to do a logical "and". Many people would prefer that you use the binary "and" operator (&) instead -- Personally, I prefer to be even more explicit:

A[~np.logical_and(B > 0.2, B < 0.5)]

Alternatively, the following work too:

A[(B <= 0.2) | (B >= 0.5)]
A[np.logical_or(B <= 0.2, B >= 0.5)]

Upvotes: 3

Related Questions