1def moving_average(a, n=3) :
2 ret = np.cumsum(a, dtype=float)
3 ret[n:] = ret[n:] - ret[:-n]
4 return ret[n - 1:] / n
5
6>>> a = np.arange(20)
7>>> moving_average(a)
8array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.,
9 12., 13., 14., 15., 16., 17., 18.])
10>>> moving_average(a, n=4)
11array([ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5,
12 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5])
13
1>>> import numpy
2>>> numbers = [3, 2, 8, 7]
3>>> mean = numpy.mean(numbers)
4>>> mean
55.0