Index multiple, non-adjacent ranges in numpy

后端 未结 1 1351
眼角桃花
眼角桃花 2020-11-29 06:12

I\'d like to select multiple, non-adjacent ranges from a 1d numpy array (or vector).

Suppose:

>>> idx = np.random.randint(100, size=10)
arra         


        
相关标签:
1条回答
  • 2020-11-29 06:37

    You need to concatenate, either before or after indexing. np.r_ makes it easy

    In [116]: idx=np.array([82,  9, 11, 94, 31, 87, 43, 77, 49, 50])
    In [117]: np.r_[0:3,7:10]
    Out[117]: array([0, 1, 2, 7, 8, 9])
    In [118]: idx[np.r_[0:3,7:10]]
    Out[118]: array([82,  9, 11, 77, 49, 50])
    

    np.r_ expands the slices and concatenates them.

    You can mix slices and lists:

    In [120]: np.r_[0:3,7:10,[0,3,4]]
    Out[120]: array([0, 1, 2, 7, 8, 9, 0, 3, 4])
    

    Concatenating before indexing is probably faster than after, but for 1d array like this, I don't think the difference is significant.

    0 讨论(0)
提交回复
热议问题