There is a great trick with stride_tricks , you can find framing functions with different generalities on SO and others (currently not in numpy), here is a version adapted to what you got:
def rolling_window(arr, window): """Very basic multi dimensional rolling window. window should be the shape of of the desired subarrays. Window is either a scalar or a tuple of same size as `arr.shape`. """ shape = np.array(arr.shape*2) strides = np.array(arr.strides*2) window = np.asarray(window) shape[arr.ndim:] = window
Note that view contains the same data as the original array! This may lead to unexpected results. But it seems to you that you only need a diagonal, you can do this with tricks with steps to make sure that you do not copy the data if you want (in future versions a view with diagonal , old ones are always a copy):
diagonal = np.diagonal(view, axis1=0, axis2=1)
Now diagonal is the array that you created in the for loop (in new versions add .copy() if you don't want a view).
Edit: since the slices array is 2D, not 3D, because you are adding, there have been no changes:
slices = diagonal.reshape(-1,2)
It may not be so fast if you have such small arrays, but its constant (waiting to copy data in a diagonal call) with the size of the array.
source share