numpy.lib.stride_tricks.as_strided stricks (abbreviation for pun intended) again!
Speaking of bizarre indexing tricks, there is the notorious np.lib.stride_tricks.as_strided . The idea / trick would be to get the cut off part, starting from the first column, to the second last and concatenation at the end. This ensures that we can move forward when necessary to use np.lib.stride_tricks.as_strided and thus avoid the need for an actual rollback. This is the whole idea!
Now, in terms of actual implementation, we will use scikit-image view_as_windows to elegantly use np.lib.stride_tricks.as_strided under the hoods. So the final implementation will be -
from skimage.util.shape import view_as_windows as viewW def strided_indexing_roll(a, r):
Hereโs a run sample -
In [327]: A = np.array([[4, 0, 0], ...: [1, 2, 3], ...: [0, 0, 5]]) In [328]: r = np.array([2, 0, -1]) In [329]: strided_indexing_roll(A, r) Out[329]: array([[0, 0, 4], [1, 2, 3], [0, 5, 0]])
Benchmarking
Let me do some benchmarking on an array with lots of rows and columns -
In [324]: np.random.seed(0) ...: a = np.random.rand(10000,1000) ...: r = np.random.randint(-1000,1000,(10000))