Moving average or running mean

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

    Python standard library solution

    This generator-function takes an iterable and a window size N and yields the average over the current values inside the window. It uses a deque, which is a datastructure similar to a list, but optimized for fast modifications (pop, append) at both endpoints.

    from collections import deque
    from itertools import islice
    
    def sliding_avg(iterable, N):        
        it = iter(iterable)
        window = deque(islice(it, N))        
        num_vals = len(window)
    
        if num_vals < N:
            msg = 'window size {} exceeds total number of values {}'
            raise ValueError(msg.format(N, num_vals))
    
        N = float(N) # force floating point division if using Python 2
        s = sum(window)
        
        while True:
            yield s/N
            try:
                nxt = next(it)
            except StopIteration:
                break
            s = s - window.popleft() + nxt
            window.append(nxt)
            
    

    Here is the function in action:

    >>> values = range(100)
    >>> N = 5
    >>> window_avg = sliding_avg(values, N)
    >>> 
    >>> next(window_avg) # (0 + 1 + 2 + 3 + 4)/5
    >>> 2.0
    >>> next(window_avg) # (1 + 2 + 3 + 4 + 5)/5
    >>> 3.0
    >>> next(window_avg) # (2 + 3 + 4 + 5 + 6)/5
    >>> 4.0
    

提交回复
热议问题