Home >Backend Development >Python Tutorial >How to Efficiently Calculate a Rolling Average in Python with NumPy?

How to Efficiently Calculate a Rolling Average in Python with NumPy?

Susan Sarandon
Susan SarandonOriginal
2024-11-16 08:16:03203browse

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:

  • Simplicity over Functionality: NumPy strives to retain a simple and compact core, avoiding unnecessary bloat from specialized functions.
  • Availability of User-Implemented Solutions: As demonstrated above, implementing a moving average with NumPy is straightforward, making it unnecessary to duplicate functionality in the library.

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!

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