Home > Backend Development > Python Tutorial > How to Calculate a Running Mean (Moving Average) in Python Using NumPy?

How to Calculate a Running Mean (Moving Average) in Python Using NumPy?

Susan Sarandon
Release: 2024-11-27 19:16:11
Original
292 people have browsed it

How to Calculate a Running Mean (Moving Average) in Python Using NumPy?

Running Mean in Python with NumPy

Calculating the running mean, also known as the moving average, of a 1D array is a common task in data analysis. NumPy provides a powerful tool called np.convolve for performing convolution operations, including the running mean.

Definition and Implementation:

The running mean involves sliding a window along the input array and computing the mean of the values within the window at each step. In NumPy, this is achieved as follows:

import numpy as np

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
window_size = 3

result = np.convolve(array, np.ones(window_size) / window_size, mode='valid')
Copy after login

Explanation:

  • np.ones(window_size) creates an array of ones with size equal to the window size.
  • np.ones(window_size) / window_size normalizes the array by dividing each element by the window size, resulting in a kernel for computing the arithmetic mean.
  • np.convolve takes the kernel and convolves it with the input array, performing a sliding mean calculation.
  • mode='valid' specifies that only the portion of the array that can be completely covered by the window should be returned, resulting in a result of size len(array) - window_size 1.

Edge Handling:

The mode argument in np.convolve controls how the edges of the array are handled during convolution. The available modes are 'full', 'same', and 'valid':

  • 'full' includes both the original length and appended zeros.
  • 'same' appends zeros until the output shape is the same as the input shape.
  • 'valid' only includes the portion of the array that can be completely covered by the window.

The 'valid' mode is typically used for the running mean, as it provides a result that does not include the windowed sections of the beginning and end of the array.

Example:

In the example above, the result will be:

[4.  5.  6.  7.  8.  9.]
Copy after login

This represents the running mean of the input array with a window size of 3.

The above is the detailed content of How to Calculate a Running Mean (Moving Average) in Python Using 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