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!