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

狂风中的少年 提交于 2020-01-30 08:41:51

问题


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, 6, 11]
for start in starts:
    dates[start:start + pattern.size] = pattern

> [0 0 1 2 3 0 1 2 3 0 0 1 2 3 0]

I have to do this many (100M+) times on large (10K+) arrays, so I'm looking for a way to do this with broadcasting or another efficient method, avoiding a for loop. pattern will always be a range if that helps.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/55716011/assign-a-sequence-at-irregular-intervals-in-1d-array-python-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!