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,
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
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.