Hi all,
Currently working on implementing an anomaly detection algorithm in python, but strangely I found myself blocked by the lack of function for moving average and similar function that exists in matlab.
Has anyone else encountered the same issue?
Best regards
Moving average is just convolution with ones(). Maybe there could be a convenience function? Or do you want to do things other than average? Would pandas work?
A moving average may interpreted as a FIR-Filter. Hence, lfilter is probably the easiest way to implement it:
import numpy as np
from scipy.signal import lfilter
m = 4 # length of averaging block
x = np.arange(10) # x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = lfilter(np.ones(m) / m, 1, x) # y = [0. , 0.25, 0.75, 1.5 , 2.5 , 3.5 , 4.5 , 5.5 , 6.5 , 7.5 ]
yeah, this comes up a lot when people jump from matlab to python — there is a moving average, it’s just not wrapped in a single obvious function. python tends to give you primitives instead of opinionated helpers. for a sliding window, numpy.lib.stride_tricks.sliding_window_view is the cleanest low-level option, and it’s fast if you know what you’re doing. for signal-style work, scipy.signal.lfilter is honestly the closest mental match to matlab’s filter pipeline.
if you’re doing anomaly detection, I’d also look at whether you actually want a simple moving average or something more stable like an EWMA (pandas.Series.ewm) or even a convolution-based approach. pandas gets dismissed sometimes, but for time-series it’s ridiculously ergonomic and performant enough in most real cases.
tl;dr: python absolutely has the tools — they’re just more composable than matlab’s one-liners. once that clicks, the flexibility is actually a win.