Moving average or running mean

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

    I feel this can be elegantly solved using bottleneck

    See basic sample below:

    import numpy as np
    import bottleneck as bn
    
    a = np.random.randint(4, 1000, size=100)
    mm = bn.move_mean(a, window=5, min_count=1)
    
    • "mm" is the moving mean for "a".

    • "window" is the max number of entries to consider for moving mean.

    • "min_count" is min number of entries to consider for moving mean (e.g. for first few elements or if the array has nan values).

    The good part is Bottleneck helps to deal with nan values and it's also very efficient.

提交回复
热议问题