Moving average or running mean

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

    I haven't yet checked how fast this is, but you could try:

    from collections import deque
    
    cache = deque() # keep track of seen values
    n = 10          # window size
    A = xrange(100) # some dummy iterable
    cum_sum = 0     # initialize cumulative sum
    
    for t, val in enumerate(A, 1):
        cache.append(val)
        cum_sum += val
        if t < n:
            avg = cum_sum / float(t)
        else:                           # if window is saturated,
            cum_sum -= cache.popleft()  # subtract oldest value
            avg = cum_sum / float(n)
    

提交回复
热议问题