NumPy Array: Moving Average or Running Mean

In this tutorial, we will learn how to calculate the moving average or running mean of the given NumPy array? By Pranit Sharma Last updated : May 25, 2023

What is Moving Average or Running Mean?

In statistics, a moving average (rolling average or running average) is a calculation to analyze data points by creating a series of averages of different selections of the full data set. It is also called a moving mean (MM) or rolling mean and is a type of finite impulse response filter. source

Problem Statement

Suppose that we are given a NumPy one-dimensional array and we need to calculate the moving average or running mean of this array.

Calculate Moving Average or Running Mean

To calculate the moving average or running mean, you can use numpy.convolve() method. Use the following code snippet to get the moving average or running mean NumPy array:

np.convolve(arr, np.ones(N)/N, mode='valid')

Explanation

The running mean can be considered as the mathematical operation of convolution. For the running mean, it slides a series along the input and computes the mean of the series' contents. For discrete 1D signals, convolution is the same thing, except instead of the mean you compute an arbitrary linear combination, i.e., multiply each element by a corresponding coefficient and add up the results.

Convolution is much better than a straightforward approach, but (I guess) it uses FFT and is thus quite slow. However, especially for computing, running means the following approach works fine.

Let us understand with the help of an example,

Python program to calculate moving average or running mean

# Import numpy
import numpy as np

# Creating numpy array
arr = np.array([13,32,45,33,53])

# Display original array
print("Array is:\n",arr,"\n")

# Defining a values for N
N = 10

# Finding running mean
res = np.convolve(arr, np.ones(N)/N, mode='valid')

# Display result
print("Result 1:\n",res)

# for N = 20
N = 20

# Finding running mean
res = np.convolve(arr, np.ones(N)/N, mode='valid')

# Display result
print("Result 2:\n",res)

Output

The output of the above program is:

Array is:
 [13 32 45 33 53] 

Result 1:
 [17.6 17.6 17.6 17.6 17.6 17.6]
Result 2:
 [8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8 8.8]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.