Moving average or running mean

后端 未结 27 1311
庸人自扰
庸人自扰 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 08:56

    You can use scipy.ndimage.filters.uniform_filter1d:

    import numpy as np
    from scipy.ndimage.filters import uniform_filter1d
    N = 1000
    x = np.random.random(100000)
    y = uniform_filter1d(x, size=N)
    

    uniform_filter1d:

    • gives the output with the same numpy shape (i.e. number of points)
    • allows multiple ways to handle the border where 'reflect' is the default, but in my case, I rather wanted 'nearest'

    It is also rather quick (nearly 50 times faster than np.convolve and 2-5 times faster than the cumsum approach given above):

    %timeit y1 = np.convolve(x, np.ones((N,))/N, mode='same')
    100 loops, best of 3: 9.28 ms per loop
    
    %timeit y2 = uniform_filter1d(x, size=N)
    10000 loops, best of 3: 191 µs per loop
    

    here's 3 functions that let you compare error/speed of different implementations:

    from __future__ import division
    import numpy as np
    import scipy.ndimage.filters as ndif
    def running_mean_convolve(x, N):
        return np.convolve(x, np.ones(N) / float(N), 'valid')
    def running_mean_cumsum(x, N):
        cumsum = np.cumsum(np.insert(x, 0, 0))
        return (cumsum[N:] - cumsum[:-N]) / float(N)
    def running_mean_uniform_filter1d(x, N):
        return ndif.uniform_filter1d(x, N, mode='constant', origin=-(N//2))[:-(N-1)]
    

提交回复
热议问题