Moving average or running mean

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

    For a short, fast solution that does the whole thing in one loop, without dependencies, the code below works great.

    mylist = [1, 2, 3, 4, 5, 6, 7]
    N = 3
    cumsum, moving_aves = [0], []
    
    for i, x in enumerate(mylist, 1):
        cumsum.append(cumsum[i-1] + x)
        if i>=N:
            moving_ave = (cumsum[i] - cumsum[i-N])/N
            #can do stuff with moving_ave here
            moving_aves.append(moving_ave)
    

提交回复
热议问题