Moving average or running mean

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

    For educational purposes, let me add two more Numpy solutions (which are slower than the cumsum solution):

    import numpy as np
    from numpy.lib.stride_tricks import as_strided
    
    def ra_strides(arr, window):
        ''' Running average using as_strided'''
        n = arr.shape[0] - window + 1
        arr_strided = as_strided(arr, shape=[n, window], strides=2*arr.strides)
        return arr_strided.mean(axis=1)
    
    def ra_add(arr, window):
        ''' Running average using add.reduceat'''
        n = arr.shape[0] - window + 1
        indices = np.array([0, window]*n) + np.repeat(np.arange(n), 2)
        arr = np.append(arr, 0)
        return np.add.reduceat(arr, indices )[::2]/window
    

    Functions used: as_strided, add.reduceat

提交回复
热议问题