1

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 !

3
  • NOT GREATER THAN is the same thing as LESS THAN OR EQUAL TO and NOT LESS THAN is the same thing as GREATER THAN OR EQUAL TO Commented May 26, 2016 at 18:52
  • @EliSadoff: Yes I am aware of that, so what is the solution? Commented May 26, 2016 at 18:55
  • It's working fine, but there does not exist a value that is both < 0.2 and >0.5 which is what your code is asking for. Commented May 26, 2016 at 18:57

2 Answers 2

3

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)]
Sign up to request clarification or add additional context in comments.

4 Comments

Oh!! What is this sorcery!! I was never aware of the invert operator ! Only the not operator seems to be available in the docs, why haven't they mentioned about ~ ? Any idea?
Python supports a full suite of "bitwise" operators (|, &, ~, ^, >>, <<). For builtin types, they're only implemented to work with int, long. (Some of the operators work on set objects too). For boolean numpy arrays, ~, | and & are overloaded to perform the logical equivalents -- Otherwise, I think they only work on integer arrays.
What was the reason you said not to use * and instead use np.logical_and ? Aren't they the same?
@ThePredator -- It does the same thing, but when reading the code, if I see a *, I don't think of logical "and" so it forces me to step back and try to figure out the expression to get an understanding of what it does.
1

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)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.