Deque上的Python标准偏差

时间:2013-09-29 19:32:45

标签: python deque moving-average standard-deviation

我使用Python deque数据类型计算简单移动平均线,我想知道有没有办法让它将它视为某种类型的数组并找到deque的标准偏差?

1 个答案:

答案 0 :(得分:1)

是的,您可以将 deque 视为数组。它既可迭代又可索引:-)

下面是一个计算滑动平均值为5的移动平均值和移动标准偏差的示例:

>>> from random import randrange
>>> from collections import deque
>>> from statistics import mean, stdev

>>> window = deque((randrange(100) for i in range(5)), 5)
>>> print(mean(window), stdev(window))
55.4 30.104816890325043
>>> for i in range(10):
        x = randrange(100)
        window.append(x)
        print(mean(window), stdev(window))

49.4 26.782456944798774
42.8 28.74369496080836
53 19.557607215607945
44.6 15.208550226763892
44.2 14.75466028073842
37.4 18.716303053755034
47.4 22.142718893577637
36.2 29.609120216581918
29.2 33.80384593504118
30 34.66266002487403

对于较大的窗口,可以通过保持运行总计来更有效地计算移动平均值和标准偏差。参见John Cook的this blog post deque 可以通过快速访问正在逐出的元素和正在运行的元素来轻松更新运行总计:

>>> window = deque((randrange(100) for i in range(5)), 5)
>>> for i in range(10):
        print(window, end='\t')
        old = window[0]
        new = randrange(100)
        window.append(new)
        print(f'Out with the {old}. In with the {new}')

deque([8, 53, 59, 86, 34], maxlen=5)    Out with the 8. In with the 58
deque([53, 59, 86, 34, 58], maxlen=5)   Out with the 53. In with the 81
deque([59, 86, 34, 58, 81], maxlen=5)   Out with the 59. In with the 31
deque([86, 34, 58, 81, 31], maxlen=5)   Out with the 86. In with the 21
deque([34, 58, 81, 31, 21], maxlen=5)   Out with the 34. In with the 11
deque([58, 81, 31, 21, 11], maxlen=5)   Out with the 58. In with the 91
deque([81, 31, 21, 11, 91], maxlen=5)   Out with the 81. In with the 42
deque([31, 21, 11, 91, 42], maxlen=5)   Out with the 31. In with the 97
deque([21, 11, 91, 42, 97], maxlen=5)   Out with the 21. In with the 94
deque([11, 91, 42, 97, 94], maxlen=5)   Out with the 11. In with the 29