Implementing Moving Averages with Python
Despite the absence of a dedicated function for calculating moving averages in NumPy or SciPy, there is a simple and efficient way to implement it using the np.cumsum function. This approach is particularly effective for non-weighted moving averages.
def moving_average(a, n=3): ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n
This code takes an array a and a window size n to calculate the moving average. It uses np.cumsum to calculate the cumulative sum of the array and then subtracts the sum of the previous n elements to adjust for the moving window. The resulting array is then divided by n to get the average.
For example, the following code computes the moving average of an array:
a = np.arange(20) moving_average(a) # array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., # 12., 13., 14., 15., 16., 17., 18.])
It is worth noting that implementing moving averages is relatively straightforward in NumPy, and the inclusion of such functionality in the library may not be necessary, as it could lead to bloat and reduce the library's focus on its core functionality.
The above is the detailed content of How to Implement Moving Averages in Python without a Dedicated Function?. For more information, please follow other related articles on the PHP Chinese website!