Moving average or running mean

后端 未结 27 1345
庸人自扰
庸人自扰 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条回答
  •  Happy的楠姐
    2020-11-22 09:16

    Another solution just using a standard library and deque:

    from collections import deque
    import itertools
    
    def moving_average(iterable, n=3):
        # http://en.wikipedia.org/wiki/Moving_average
        it = iter(iterable) 
        # create an iterable object from input argument
        d = deque(itertools.islice(it, n-1))  
        # create deque object by slicing iterable
        d.appendleft(0)
        s = sum(d)
        for elem in it:
            s += elem - d.popleft()
            d.append(elem)
            yield s / n
    
    # example on how to use it
    for i in  moving_average([40, 30, 50, 46, 39, 44]):
        print(i)
    
    # 40.0
    # 42.0
    # 45.0
    # 43.0
    

提交回复
热议问题