Imagine an array a
which has to be indexed by multiple ranges in idx
:
In [1]: a = np.array([7,9,1,2,3,5,6,8,1,0,])
idx = np.array([[0,3],[5,7],[8,9]])
a, idx
Out[1]: (array([7, 9, 1, 2, 3, 5, 6, 8, 1, 0]),
array([[0, 3],
[5, 7],
[8, 9]]))
Of course I could write a simple for
loop, which results in the desired output:
In [2]: np.hstack([a[i[0]:i[1]] for i in idx])
Out[2]: array([7, 9, 1, 5, 6, 1])
But I would like a fully vectorized approach. I was hoping np.r_
for example would provide a solution. But the code below does not result in the desired output:
In [3]: a[np.r_[idx]]
Out[3]: array([[7, 2],
[5, 8],
[1, 0]])
Whereas writing out idx
does result in the desired output. But the real life idx
is too large to write out:
In [4]: a[np.r_[0:3,5:7,8:9]]
Out[4]: array([7, 9, 1, 5, 6, 1])