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

前端 未结 2 518
执念已碎
执念已碎 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:43

    Construct a 2D selector array to select the indices of dates you want to modify with numpy.add.outer, then perform a broadcasted assignment of pattern into the selected indices:

    dates[numpy.add.outer(starts, numpy.arange(len(pattern)))] = pattern
    
    0 讨论(0)
  • 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.

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