Moving average or running mean

后端 未结 27 1313
庸人自扰
庸人自扰 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:04

    You can calculate a running mean with:

    import numpy as np
    
    def runningMean(x, N):
        y = np.zeros((len(x),))
        for ctr in range(len(x)):
             y[ctr] = np.sum(x[ctr:(ctr+N)])
        return y/N
    

    But it's slow.

    Fortunately, numpy includes a convolve function which we can use to speed things up. The running mean is equivalent to convolving x with a vector that is N long, with all members equal to 1/N. The numpy implementation of convolve includes the starting transient, so you have to remove the first N-1 points:

    def runningMeanFast(x, N):
        return np.convolve(x, np.ones((N,))/N)[(N-1):]
    

    On my machine, the fast version is 20-30 times faster, depending on the length of the input vector and size of the averaging window.

    Note that convolve does include a 'same' mode which seems like it should address the starting transient issue, but it splits it between the beginning and end.

提交回复
热议问题