I am computing the simple moving average using the Python deque datatype, and I am wondering is there a way to have it treat this as some sort of an array and find the standard deviation of the deque?
Asked
Active
Viewed 4,412 times
4
-
1Would help if you added a concrete example of what you want. You can apply `list()` to a deque to get a plain list with the same values in the same order. Is that enough? Or do you also need code to calculate sdev? Etc. – Tim Peters Sep 29 '13 at 19:45
-
1You can iterate over a deque and you can get its length. What more do you need? – Sep 29 '13 at 20:10
-
Thanks I didn't know it was that clear I ended up doing something like dlist[n] and iterating over that. – eWizardII Sep 30 '13 at 19:18
1 Answers
5
Yes, you can treat a deque as an array. It is both iterable and indexable :-)
Here's an example of computing a moving average and moving standard deviation with a sliding window of width five:
>>> 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
For larger windows, it is possible to compute moving averages and standard deviations more efficiently by keeping running totals. See this blog post by John Cook. The deque makes it easy to update the running total by quickly accessing both the element is being evicted and the element being:
>>> 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

Raymond Hettinger
- 216,523
- 63
- 388
- 485