Moving average or running mean

后端 未结 27 1084
庸人自扰
庸人自扰 2020-11-22 08:37

Is there a SciPy function or NumPy function or module for Python that calculates the running mean of a 1D array given a specific window?

27条回答
  •  攒了一身酷
    2020-11-22 09:16

    How about a moving average filter? It is also a one-liner and has the advantage, that you can easily manipulate the window type if you need something else than the rectangle, ie. a N-long simple moving average of an array a:

    lfilter(np.ones(N)/N, [1], a)[N:]
    

    And with the triangular window applied:

    lfilter(np.ones(N)*scipy.signal.triang(N)/N, [1], a)[N:]
    

    Note: I usually discard the first N samples as bogus hence [N:] at the end, but it is not necessary and the matter of a personal choice only.

提交回复
热议问题