基于多个范围从数组中提取间隔。

问题描述 投票:1回答:1

假设我有一个名为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但现实生活中的数据集是巨大的,所以我希望尽可能的防止循环。

python arrays numpy intervals
1个回答
1
投票

考虑到输出的粗糙性,你无法避免循环。但我们应该在迭代时尽量减少计算量。所以,这里有一种方法可以在迭代时简单地对输入数组进行分片,因为我们将大部分计算部分与获取每组的开始、停止指数一起进行。searchsorted -

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

1
投票

这里有一种方法,通过广播来获取索引数组,用 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])]
© www.soinside.com 2019 - 2024. All rights reserved.