2

Looking for a more efficient way to check if items within a numpy array fall within any (or match at least once) of a set of min & max values. I toyed around with any() and np.any() and all() but these are newer concepts to me.

y_minmax_bounds = [[1.1, 2.0], [3.3, 6.21], [5.75, 10.0]]
y = np.array([1.5, 2.5, 2, 6, 8, 10])
withinbounds = [((y > min) & (y < max))for min, max in y_minmax_bounds]
print(withinbounds)

Returns:

[array([True, False, False, False, False, False]), 
array([False, False, False,  True, False, False]), 
array([False, False, False,  True,  True, False])]

After a array solution of:

[True False False True True False]

I can loop over y_minmax_bounds, but this seems inefficient given a very large np.array to check. The actual problem will also be enforcing this in multiple dimensions (x_minmax_bounds on x, z_minmax_bounds over z).

3
  • Only 10 doesn't fall between at least one interval. Commented Aug 29, 2018 at 4:50
  • Apologies - I have edited a typo in y_minmax_bounds, which also sets 2.5 and 2 as False. Commented Aug 29, 2018 at 4:56
  • The solution should still work Commented Aug 29, 2018 at 4:57

1 Answer 1

4

With Numpy broadcasting

mn, mx = np.array(y_minmax_bounds).T
x = y[:, None]

((x > mn) & (x < mx)).any(1)

array([ True, False, False,  True,  True, False])
Sign up to request clarification or add additional context in comments.

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.