How to calculate moving average in Python 3?

后端 未结 5 1634
挽巷
挽巷 2020-12-06 02:21

Let\'s say I have a list:

y = [\'1\', \'2\', \'3\', \'4\',\'5\',\'6\',\'7\',\'8\',\'9\',\'10\']

I want to create a function that calculates

5条回答
  •  独厮守ぢ
    2020-12-06 02:44

    There is another solution extending an itertools recipe pairwise(). You can extend this to nwise(), which gives you the sliding window (and works if the iterable is a generator):

    def nwise(iterable, n):
        ts = it.tee(iterable, n)
        for c, t in enumerate(ts):
            next(it.islice(t, c, c), None)
        return zip(*ts)
    
    def moving_averages_nw(iterable, n):
        yield from (sum(x)/n for x in nwise(iterable, n))
    
    >>> list(moving_averages_nw(range(1, 11), 5))
    [3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
    

    While a relatively high setup cost for short iterables this cost reduces in impact the longer the data set. This uses sum() but the code is reasonably elegant:

    Timeit              MP           cfi         *****
    --------------------------------------------------------------------------------
    10                 4.658        4.959        7.351 
    100                5.144        4.070        4.234 
    1000               5.312        4.020        3.977 
    10000              5.317        4.031        3.966 
    100000             5.508        4.115        4.087 
    1000000            5.526        4.263        4.202 
    10000000           5.632        4.326        4.242 
    

提交回复
热议问题