3

我正在使用 Python deque 数据类型计算简单的移动平均值,我想知道有没有办法让它把它当作某种数组并找到双端队列的标准偏差?

4

1 回答 1

4

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

这是一个使用宽度为 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 的这篇博文。端队列可以通过快速访问正在被驱逐的元素和正在被驱逐的元素来轻松更新运行总数:

>>> 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
于 2019-10-04T04:38:23.377 回答