[SciPy-user] moving average, moving standard deviation, etc...
Denis Simakov
akinoame1 at gmail.com
Mon Dec 25 06:32:50 CST 2006
For operations which may be reduced to sums (this includes average and
std), you can use cumulative sum:
>>> A = arange(10.0)
>>> w = 2 # window length
>>> C = zeros_like(A)
>>> B = A.cumsum()
>>> C[w:] = (B[w:] - B[:-w]) / w # running average
>>> C[:w] = B[:w] / arange(1,w+1) # just average for first elements
>>> print vstack((A, C))
[[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. ]
[ 0. 0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5]]
Denis
On 12/23/06, Matt Knox <mattknox_ca at hotmail.com> wrote:
>
> Does anyone know of a slick way to calculate a simple moving average and/or moving standard deviation? And when I say slick, I mean loop-free way, because it would be fairly easy to code a looping way of doing it, it would just be really slow.
>
> To be more specific, when I say moving standard deviation, I mean for example...
>
> if A is a 1-dimensional array with 100 elements, and I'm using a window size of 10, then the result at index 10 would be A[0:10].std(), the result at index 11 would be A[1:11].std() , etc...
>
> And similarly for moving average, and so forth. Is their a general way to do these kind of things? Or would it have to be a special case for each type of calculation to avoid looping?
>
> Any help is greatly appreciated. Thanks in advance,
>
> - Matt
More information about the SciPy-user
mailing list