3

I have two arrays, and I want to select a section of one of them based on values of the other. I know how to do this in a few lines, but I want to know if there is a neater way, in one line, to do this. This is how I do it which is long and ugly.

lower = some_value; upper = another_value
a = [some numpy array]; b = [another numpy array]
b_select = []
for i in range(len(a)):
    if a[i] < lower or a[i] > upper:
        b_select.append(b[i])

So basically my question is, can I get b_select in one line, instead of the last 4 lines?

Any advice would be much appreciated. For info I am doing this in Python 2.7.

2 Answers 2

8

The stated problem is looking to select values that are outside the bounds set by lower and upper bounds. To solve it, we can use boolean indexing -

b[(a < lower) | (a > upper)]

The other scenario to select within the lower and upper bounds, invert the process -

b[(a > lower) & (a < upper)]

To have inclusiveness on the bounds, replace <'s with <= and >'s with >=.

Sign up to request clarification or add additional context in comments.

Comments

0

Unless numpy has some strange arrays this should work:

b_select = [x for x in a if (x < lower or x > upper)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.