How to efficiently index into a 1D numpy array via slice ranges

前端 未结 2 875
情歌与酒
情歌与酒 2021-01-14 12:44

I have a big 1D array of data. I have a starts array of indexes into that data where important things happened. I want to get an array of ranges so that I get w

2条回答
  •  终归单人心
    2021-01-14 13:32

    If you need to do this a lot of time, you can use as_strided() to create a sliding windows array of data

    data = np.linspace(0,10,50000)
    length = 5
    starts = np.random.randint(0, len(data)-length, 10000)
    
    from numpy.lib.stride_tricks import as_strided
    sliding_window = as_strided(data, (len(data) - length + 1, length), 
                     (data.itemsize, data.itemsize))
    

    Then you can use:

    sliding_window[starts]
    

    to get what you want.

    It's also faster than creating the index array.

提交回复
热议问题