Moving average or running mean

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

    Use Only Python Standard Library (Memory Efficient)

    Just give another version of using the standard library deque only. It's quite a surprise to me that most of the answers are using pandas or numpy.

    def moving_average(iterable, n=3):
        d = deque(maxlen=n)
        for i in iterable:
            d.append(i)
            if len(d) == n:
                yield sum(d)/n
    
    r = moving_average([40, 30, 50, 46, 39, 44])
    assert list(r) == [40.0, 42.0, 45.0, 43.0]
    

    Actually I found another implementation in python docs

    def moving_average(iterable, n=3):
        # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
        # http://en.wikipedia.org/wiki/Moving_average
        it = iter(iterable)
        d = deque(itertools.islice(it, n-1))
        d.appendleft(0)
        s = sum(d)
        for elem in it:
            s += elem - d.popleft()
            d.append(elem)
            yield s / n
    

    However the implementation seems to me is a bit more complex than it should be. But it must be in the standard python docs for a reason, could someone comment on the implementation of mine and the standard doc?

提交回复
热议问题