Home > Backend Development > Python Tutorial > How to Implement Moving Averages in Python without a Dedicated Function?

How to Implement Moving Averages in Python without a Dedicated Function?

Linda Hamilton
Release: 2024-11-19 21:13:03
Original
711 people have browsed it

How to Implement Moving Averages in Python without a Dedicated Function?

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

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.])
Copy after login

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!

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