简体   繁体   中英

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?

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM