给定起始位置和结束位置列表构造 Numpy 索引 [英] Construct Numpy index given list of starting and ending positions
问题描述
我有两个大小相同的 numpy.array 对象(都是一维的),其中一个包含起始索引位置列表,另一个包含结束索引位置列表(或者你可以说我有起始位置和窗口长度的列表).万一重要,由起始位置和结束位置形成的切片保证不重叠.我试图弄清楚如何使用这些开始和结束位置来形成另一个数组对象的索引,而不必使用循环.
I have two identically-sized numpy.array objects (both one-dimensional), one of which contains a list of starting index positions, and the other of which contains a list of ending index positions (alternatively you could say I have a list of starting positions and window lengths). In case it matters, the slices formed by the starting and ending positions are guaranteed to be non-overlapping. I am trying to figure out how to use these starting and ending positions to form an index for another array object, without having to use a loop.
例如:
import numpy as np
start = np.array([1,7,20])
end = np.array([3,10,25])
想参考
somearray[1,2,7,8,9,20,21,22,23,24])
推荐答案
我会使用
np.r_[tuple(slice(s, e) for s, e in zip(start, end))]
这是一个不使用 Python 循环的解决方案:
Here is a solution that does not use a Python loop:
def indices(start, end):
lens = end - start
np.cumsum(lens, out=lens)
i = np.ones(lens[-1], dtype=int)
i[0] = start[0]
i[lens[:-1]] += start[1:]
i[lens[:-1]] -= end[:-1]
np.cumsum(i, out=i)
return i
这只会创建一个临时 NumPy 数组 (lens
),并且比任何其他解决方案都快得多.
This only creates a single temporary NumPy array (lens
) and is much faster than any of the other solutions.
这篇关于给定起始位置和结束位置列表构造 Numpy 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!