0

I have an array and an integer

import numpy as np

a = np.array([1,2,3,4])
b = 3

I would like to find all elements in a that are within +-diff of b. If diff=1 then I can do this using

d = np.where( (a == b - 1) | (a == b) | (a == b + 1) )
vals = a[d]

But what if diff = 2, or is undetermined and I want to create a function that has diff as an input?

I'm sure there must be a far more efficient and flexible way to code this than I have found.

I'm using Python 3.5

1 Answer 1

2

You can use inequality expression:

a[ (b + diff >= a) & (a >= b - diff) ]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, sometimes the obvious is hard to see!

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.