moving average numpy

Solutions on MaxInterview for moving average numpy by the best coders in the world

showing results for - "moving average numpy"
Mitt
13 Apr 2016
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