查找排序的浮点数组是否有效地包含一定范围内的数字 [英] Find if a sorted array of floats contains numbers in a certain range efficiently

查看:65
本文介绍了查找排序的浮点数组是否有效地包含一定范围内的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点数排序的numpy数组,我想知道此数组是否包含给定范围内的数字.请注意,我对数组中数字的位置不感兴趣.我只想知道是否有至少一个数字落在该范围内.

I have a sorted numpy array of floats, and I want to know whether this array contains number in a given range. Note that I'm not interested in the positions of the number in the array. I only want to know if there is at least one number that falls in the range.

由于我必须在大量间隔上执行相同的操作(数组在整个操作过程中保持不变),所以我担心效率.

Since I have to do the very same operation on a large numbers of intervals (the array remains constant during the entire operation), I'm concerned about the efficiency.

有人可以帮助我吗?

推荐答案

如评论中所述,

As talked about in the comments, np.searchsorted could be useful and indeed it is. As stated in the question, the array stays the same, while we have different ranges across iterations. So, let's say the ranges are stored in a (n,2) shaped array, such that the first column represents the start, while the second column are the stop values of those ranges.

我们会用np.searchsorted解决方案,就像这样-

We would have a solution with np.searchsorted, like so -

np.searchsorted(a,ranges[:,0]) != np.searchsorted(a,ranges[:,1])

这个想法是,如果一个范围内有任何数字,那么使用第一列找到的排序索引(起始值)将小于并且因此不等于第二列中的索引(终止值).

The idea is that if there's any number within a range, then the sorted indices found using the first column (start values) would be lesser than and thus not equal to the indices from the second column (stop values).

样品运行-

In [75]: a   # Input data array
Out[75]: 
array([ 13.,  20.,  22.,  24.,  36.,  50.,  52.,  60.,  64.,  65.,  65.,
        66.,  72.,  76.,  81.,  84.,  88.,  88.,  90.,  97.])

In [76]: ranges # Array of ranges
Out[76]: 
array([[ 19.,  26.],
       [ 22.,  33.],
       [ 25.,  35.],
       [ 38.,  62.]])

In [77]: np.searchsorted(a,ranges[:,0]) != np.searchsorted(a,ranges[:,1])
Out[77]: array([ True,  True, False,  True], dtype=bool)

这篇关于查找排序的浮点数组是否有效地包含一定范围内的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆