简体   繁体   中英

Index numpy array with multiple ranges

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

You can try vectorizing slice itself:

>>> slice_np = np.vectorize(slice)
>>> slice_idx = tuple(slice_np(idx[:, 0], idx[:, 1]))
>>> a[np.r_[slice_idx]]
 array([7, 9, 1, 5, 6, 1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM