Categories
Python Answers

How to get rolling window for 1D arrays in Python Numpy?

Spread the love

Sometimes, we want to get rolling window for 1D arrays in Python Numpy.

In this article, we’ll look at how to get rolling window for 1D arrays in Python Numpy.

How to get rolling window for 1D arrays in Python Numpy?

To get rolling window for 1D arrays in Python Numpy, we can use the sliding_window_view function.

For instance, we write

from numpy.lib.stride_tricks import sliding_window_view

rolling_window = sliding_window_view(np.array([1, 2, 3, 4, 5, 6]), window_shape = 3)

to calli sliding_window_view on the NumPy array that we get by calling np.array on a list.

We set the window_shape argument to 3 to return a rolling window list with 3 numbers in each nested list.

Conclusion

To get rolling window for 1D arrays in Python Numpy, we can use the sliding_window_view function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *