Assign a sequence at irregular intervals in 1D array - Python / NumPy

前端 未结 2 516
执念已碎
执念已碎 2021-01-23 08:08

I have a sequence of numbers that I would like to insert into a larger array at irregular intervals:

dates = np.zeros(15)
pattern = np.arange(3) + 1
starts = [2,         


        
2条回答
  •  孤城傲影
    2021-01-23 08:45

    We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windowed views into the output array and hence assign the new values into it. This would be pretty efficient, as we are working with views, there's no generation of explicit indices and the assignment is a vectorized and broadcasted one.

    The implementation would look something like this -

    from skimage.util.shape import view_as_windows
    
    view_as_windows(dates,pattern.size)[starts] = pattern
    

    More info on use of as_strided based view_as_windows.

提交回复
热议问题