6

I have a numpy array, called a , I want to check whether it contains an item in a range, specified by two values.

import numpy as np
a = np.arange(100)

mintrshold=33
maxtreshold=66

My solution:

goodItems = np.zeros_like(a)
goodItems[(a<maxtreshold) & (a>mintrshold)] = 1

if goodItems.any(): 
   print (there s an item within range)

Can you suggest me a more effective, pythonic way?

3
  • 1
    I don't know about numpy per se, but with normal python list I'd write it like; if any(mintrshold < x <= maxtreshold for x in a): print('True') Commented May 31, 2017 at 10:25
  • Since you are interested in finding if any item exists: as a general recommendation, use a generator expression with any if you expect to find a valid item early in the array - being able to return True without iterating through the whole array can save a lot of runtime. Use a numpy expression with .any() if you don't expect an item early or at all. Always benchmark with real data. Commented Aug 7, 2023 at 5:37
  • Does this answer your question? Numpy: find index of the elements within range Commented Aug 7, 2023 at 20:53

2 Answers 2

10

Numpy arrays doesn't work well with pythonic a < x < b. But there's func for this:

np.logical_and(a > mintrshold, a < maxtreshold)

or

np.logical_and(a > mintrshold, a < maxtreshold).any()

in your particular case. Basically, you should combine two element-wise ops. Look for logic funcs for more details

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

1 Comment

Thank you, it is more elegant and 2.5 times faster than my naive solution.
2

Adding to the pure Numpy answer we can also use itertools

import itertools

bool(list(itertools.ifilter(lambda x: 33 <= x <= 66, a)))

For smaller arrays this would suffice:

bool(filter(lambda x: 33 <= x <= 66, a))

7 Comments

I tried your second line, but it does not work, always ends up being True
I thought that was the desired output, to return True if numbers in the array do fall within the condition. If you need list/array of bools returned let me know and I can modify it for that.
You interpreted my question well,but if a=np.arange(100,120), your second line still returns True
It returns False for me, I think maybe you are copying or typing something incorrectly. Both of my one-liners return False given that a=np.arange(100,120)
I tried your second oneliner with pyton 3.6, it returns True, in python 2.5 it returns False (a=np.arange(100,120)):D. I only checked it with 3.6 only yesterday.
|

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.