Categories

# How to take subarrays from Python numpy array with given stride/step size?

Sometimes, we want to take subarrays from Python numpy array with given stride/step size.

In this article, we’ll look at how to take subarrays from Python numpy array with given stride/step size.

### How to take subarrays from Python numpy array with given stride/step size?

To take subarrays from Python numpy array with given stride/step size, we can use the `lib.atride_ticks.as_strided` method.

For instance, we write:

``````import numpy as np

def strided_app(a, L, S):
nrows = ((a.size - L) // S) + 1
n = a.strides
return np.lib.stride_tricks.as_strided(a,
shape=(nrows, L),
strides=(S * n, n))

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
s = strided_app(a, L=5, S=3)
print(s)
``````

We create the `strided_app` function that takes the array `a`.

`L` is the length of the chunk.

And `S` is the stride or step size.

We compute the number of rows with `((a.size - L) // S) + 1`.

Then we get the first chunk with `a.strides`.

And then we call `np.lib.stride_tricks.as_strided` to compute the chunks with the `shape` of the nested array and the `strides` set to the start and end index of the range of items from the original array used to form the chunks in the new array.

Therefore, `s` is:

``````[[ 1  2  3  4  5]
[ 4  5  6  7  8]
[ 7  8  9 10 11]]
``````

### Conclusion

To take subarrays from Python numpy array with given stride/step size, we can use the `lib.atride_ticks.as_strided` method.