Example 1: moving average numpy
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
>>> a = np.arange(20)
>>> moving_average(a)
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.,
12., 13., 14., 15., 16., 17., 18.])
>>> moving_average(a, n=4)
array([ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5,
10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5])
Example 2: python moving average of list
import numpy
def running_mean(x, N):
""" x == an array of data. N == number of samples per average """
cumsum = numpy.cumsum(numpy.insert(x, 0, 0))
return (cumsum[N:] - cumsum[:-N]) / float(N)
val = [-30.45, -2.65, 56.61, 47.13, 47.95, 30.45, 2.65, -28.31, -47.13, -95.89]
print(running_mean(val, 3))
""" [ 7.83666667 33.69666667 50.56333333 41.84333333 27.01666667
1.59666667 -24.26333333 -57.11 ] """