Search code examples
pythonarraysnumpystride

Creating overlapping subarrays using stride_tricks


I found the below code that creates overlapping subarrays of a given length. It does what I want except that it also reverses the order of the elements, which I do not want. I couldn't really find documentation on the 'shape' and 'strides' arguments and so do not know how to change that behavior. How do I change the 'out = ...' line so that the elements are not reversed?

import numpy as np

x = np.array([2,3,1,0])
L = 3 # Row length
strided = np.lib.stride_tricks.as_strided
n = x.strides[0]
out = strided(x[L-1:],shape=(x.size-L+1,L),strides=(n,-n))
print out

Solution

  • you need to keep all the data :

    out = strided(x,shape=(x.size-L+1,L),strides=(n,n))
    

    For

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

    strided don't check that access is in the scope, so in case of mistake everything can happen.