Home >Backend Development >Python Tutorial >How to Efficiently Calculate a Rolling Average in Python with NumPy?
Calculating Rolling / Moving Average in Python with NumPy / SciPy
Despite the extensive functionality of NumPy and SciPy, calculating a moving average can be a surprisingly complex task. This article tackles the issue by providing an easy-to-implement solution using NumPy's np.cumsum.
Easiest Way to Implement Moving Average with NumPy
For a straightforward non-weighted moving average, np.cumsum provides an efficient solution:
def moving_average(a, n=3): ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n
Performance and Simplicity
This method offers high performance as it leverages NumPy's optimized np.cumsum function, outperforming FFT-based methods in certain cases. Additionally, it avoids potential errors associated with complex algorithms, making it highly reliable.
Rational for Excluding Moving Average Functionality in NumPy
Despite its apparent utility, there may be valid reasons for excluding moving average functionality from core NumPy:
The above is the detailed content of How to Efficiently Calculate a Rolling Average in Python with NumPy?. For more information, please follow other related articles on the PHP Chinese website!