我有一个整数的numpy数组。
我还有另外两个数组,分别代表该数组的开始和长度(或者可以是开始和结束)索引,这些索引标识了我需要处理的整数序列。序列是可变长度的。
x=numpy.array([2,3,5,7,9,12,15,21,27,101, 250]) #Can have length of millions
starts=numpy.array([2,7]) # Can have lengths of thousands
ends=numpy.array([5,9])
# required output is x[2:5],x[7:9] in flat 1D array
# [5,7,9,12,21,27,101]
我可以使用for循环轻松地做到这一点,但是应用程序对性能很敏感,因此我正在寻找一种无需Python迭代即可做到的方法。
非常感谢您的帮助!
道格
一种矢量化方法是通过广播创建掩膜-
In [16]: r = np.arange(len(x))
In [18]: x[((r>=starts[:,None]) & (r<ends[:,None])).any(0)]
Out[18]: array([ 5, 7, 9, 21, 27])
[另一种基于循环的实现内存效率的方法,在starts,ends
对中有很多条目可能会更好-
mask = np.zeros(len(x),dtype=bool)
for (i,j) in zip(starts,ends):
mask[i:j] = True
out = x[mask]
为了完整起见,这是另一个with循环,用于选择切片,然后将其分配到初始化的数组中,并且应该适合于从大型数组中选择的小切片-
lens = ends-starts
out = np.empty(lens.sum(),dtype=x.dtype)
start = 0
for (i,j,l) in zip(starts,ends,lens):
out[start:start+l] = x[i:j]
start += l