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.