Moving average or running mean

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

    Although there are solutions for this question here, please take a look at my solution. It is very simple and working well.

    import numpy as np
    dataset = np.asarray([1, 2, 3, 4, 5, 6, 7])
    ma = list()
    window = 3
    for t in range(0, len(dataset)):
        if t+window <= len(dataset):
            indices = range(t, t+window)
            ma.append(np.average(np.take(dataset, indices)))
    else:
        ma = np.asarray(ma)
    

提交回复
热议问题