How to calculate rolling / moving average using python + NumPy / SciPy?

If you just want a straightforward non-weighted moving average, you can easily implement it with np.cumsum, which may be is faster than FFT based methods: EDIT Corrected an off-by-one wrong indexing spotted by Bean in the code. EDIT def moving_average(a, n=3) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] – ret[:-n] return ret[n – 1:] … Read more

Moving average or running mean

UPDATE: more efficient solutions have been proposed, uniform_filter1d from scipy being probably the best among the “standard” 3rd-party libraries, and some newer or specialized libraries are available too. You can use np.convolve for that: np.convolve(x, np.ones(N)/N, mode=”valid”) Explanation The running mean is a case of the mathematical operation of convolution. For the running mean, you … Read more

Calculating moving average

Or you can simply calculate it using filter, here’s the function I use: ma <- function(x, n = 5){filter(x, rep(1 / n, n), sides = 2)} If you use dplyr, be careful to specify stats::filter in the function above.