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

Susan Sarandon
Release: 2024-11-16 08:16:03
Original
137 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template