2013-04-08 32 views
1

選擇範圍我有兩個數組被用作指標NumPy的高級索引

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解決方案

回答

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] 
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])