根据多个范围从数组中检索间隔

Retrieve intervals from array based on multiple ranges

假设我有一个名为 a:

的 Numpy 数组
a = np.array([2,3,8,11,30,39,44,49,55,61])

我想根据另外两个数组检索多个间隔:

l = np.array([2,5,42])
r = np.array([10,40,70])

做与此等效的事情:

a[(a > l) & (a < r)]

将此作为所需的输出:

Out[1]: [[3 8],[ 8 11 30 39],[44 49 55 61]]

当然我可以做一个简单的 for 循环遍历 lr,但现实生活中的数据集很大,所以我想尽可能避免循环可能的。

鉴于输出参差不齐的特性,您无法避免循环。但是我们应该在迭代时尽量减少计算。因此,这是一种在迭代时简单地切入输入数组的方法,因为我们将大部分计算部分与开始,停止每组索引 searchsorted -

lidx = np.searchsorted(a,l,'right')
ridx = np.searchsorted(a,r,'left')
out = [a[i:j] for (i,j) in zip(lidx,ridx)]

这是一种方法,广播获取索引数组,并使用np.split拆分数组:

# generates a (3,len(a)) where the windows are found in each column
w = (a[:,None] > l) & (a[:,None] < r)
# indices where in the (3,len(a)) array condition is satisfied
ix, _ = np.where(w)
# splits according to the sum along the columns
np.split(a[ix], np.cumsum(w.sum(0)))[:-1]
# [array([3, 8]), array([ 8, 11, 30, 39]), array([44, 49, 55, 61])]