Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check efficiently numpy array contains item within given range?

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?

like image 838
user3598726 Avatar asked Dec 19 '22 07:12

user3598726


1 Answers

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

like image 55
Slam Avatar answered Dec 21 '22 11:12

Slam