1

我有两个用作索引的数组

a = np.array([0, 5, 11])
b = np.array([2, 8, 13])

如何选择这些数组之间的范围?即 0 - 2, 5 - 8, 11 - 13

c = np.array([0,1,2,5,6,7,8,11,12,13])

这样我就可以使用

data[c] # selects all the elements between ranges a and b

如何构造数组c?我正在寻找一个 numpy 解决方案

4

2 回答 2

4
>>> x = np.arange(20)
>>> a = [0, 5, 11]
>>> b = [2, 8, 13]
>>> np.hstack(x[start:stop+1] for start, stop in zip(a, b))
array([ 0,  1,  2,  5,  6,  7,  8, 11, 12, 13])
于 2013-04-08T13:09:32.073 回答
3
>>> zip(a, b)
[(0, 2), (5, 8), (11, 13)]

>>> [range(l,h+1) for l,h in zip(a, b)]
[[0, 1, 2], [5, 6, 7, 8], [11, 12, 13]]

>>> list(itertools.chain.from_iterable(range(l,h+1) for l,h in zip(a, b)))
[0, 1, 2, 5, 6, 7, 8, 11, 12, 13]
于 2013-04-08T13:07:32.760 回答