-1

My code tries to calculate a moving average of a list, but it computes it incorrectly. Here is the code:

import numpy as np
import matplotlib.pyplot as plt


for i in a:
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)
    display(Mov_Avg)

plt.plot(Mov_Avg)
User123
  • 29
  • 9

2 Answers2

0

You should loop over the elements of range(len(a)) and not over the elements of a directly.

import numpy as np
import matplotlib.pyplot as plt

a = np.array([5,3,8,10,2,1,5,1,0,2])
window_size = 2
plt.plot(a)

Mov_Avg = [] #Empty list that will hold the resulting moving averages

for i in range(len(a)):
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)

plt.plot(Mov_Avg)
0

I see two issues here:

  • Since you're doing a moving average, once you get to the indices which are less than window_size away from the end of the array a, you'll be out of bound.
  • for i in a doesn't give you indices to access the array a but the actual values inside the array.

What you want to do is something like this:

import numpy as np

a = np.array([5,3,8,10,2,1,5,1,0,2])
window_size = 2

Mov_Avg = []

for i in range(a.size - window_size + 1):
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)

Which gives:

>>> print(a)
[ 5  3  8 10  2  1  5  1  0  2]
>>> print(Mov_Avg)
[4.0, 5.5, 9.0, 6.0, 1.5, 3.0, 3.0, 0.5, 1.0]

Note that since here window_size == 2, you get len(Mov_Avg) == a.size - 1. The general case is in the range above. What you can do to get something a bit cleaner when plotting is this:

x_a = np.arange(a.size)
x_Mov_Avg = (x_a + (window_size-1)/2)[:-(window_size-1)]
plt.plot(x_a, a)
plt.plot(x_Mov_Avg, Mov_Avg)
plt.show()

This will show the moving average data points at the center of their windows along the x axis.

Jenny
  • 601
  • 3
  • 11