Skip to content Skip to sidebar Skip to footer

Moving Average Of 3 Elements By C Or Python

I want to calculate the moving average of 3 elements. For example, I have a 25 elements of sales data. I need to calculate the moving average taken from averaging these 25 element

Solution 1:

The best (and fastest, by far) way to approach this is convolution. Using numpy's convolve:

import numpy as np

x = np.asarray([7.0, 9.0, 5.0, 1.0, 3.0])

# create what's known as the convolution 'kernel'# note that this sums to 1, which results in an average
kernel = np.ones(3) / 3# do the convolution to compute the moving average
moving_avg = np.convolve(x, kernel, mode='valid')

You can view the convolution operation as the kernel "sliding" over the data sequence. Every point moving_avg[k] in the output of the convolution will be the area under the product between your data and the kernel, when the kernel is centered at that point k.

This is an animation (from the wikipedia article linked above) illustrating the principle for the square kernel used in moving average computation:

enter image description here

Solution 2:

A list comprehension is a pythonic way to do this, that does not require any import:

>>> a[7, 9, 5, 1, 3]
>>> [(a[i]+a[i+1]+a[i+2])/3.0 for i in xrange(len(a)-2)]
[7.0, 5.0, 3.0]

Solution 3:

You could use a Python deque for doing this as follows:

from collections import deque

prices = [7.0, 9.0, 5.0, 1.0, 3.0]
moving_average = deque()
total = 0.0
days = 3
averages = []

for price in prices:
    moving_average.append(price)
    total += price

    iflen(moving_average) > days:      # Length of moving average
        total -= moving_average.popleft()

    averages.append(total / float(len(moving_average)))

print averages

This would display the following output:

[7.0, 8.0, 7.0, 5.0, 3.0]

Or you could skip the initial entries as follows:

print averages[days-1:]

Giving:

[7.0, 5.0, 3.0]

Post a Comment for "Moving Average Of 3 Elements By C Or Python"