Home  >  Article  >  Backend Development  >  How Can I Calculate Rolling Standard Deviation on a 1D NumPy Array Using a Rolling Window?

How Can I Calculate Rolling Standard Deviation on a 1D NumPy Array Using a Rolling Window?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 12:33:01533browse

How Can I Calculate Rolling Standard Deviation on a 1D NumPy Array Using a Rolling Window?

Rolling Window Implementation for 1D Arrays in NumPy

For efficient handling of rolling windows on 1D arrays, NumPy provides a useful implementation. Let's consider a scenario where we have a 1D NumPy array called observations. To calculate the rolling standard deviations with a window length of n, we can leverage the following approach:

<code class="python">import numpy as np

n = 5  # Example window length

# Create a rolling window for the observations
rolling_window = np.lib.stride_tricks.as_strided(observations, shape=(len(observations) - n + 1, n), strides=(observations.strides[0],))

# Apply the standard deviation function to each window
rolling_stdev = np.std(rolling_window, axis=1)</code>

This code snippet efficiently applies the NumPy std function to each window, resulting in the desired rolling standard deviation values. Note that you can replace np.std with any other function you wish to apply to the windowed data.

The above is the detailed content of How Can I Calculate Rolling Standard Deviation on a 1D NumPy Array Using a Rolling Window?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn