time series calculation in list comprehension?
Jim Segrave
jes at nl.demon.net
Sun Mar 12 10:00:02 EST 2006
In article <1142012049.892323.103060 at v46g2000cwv.googlegroups.com>,
falcon <shahbazc at gmail.com> wrote:
>Is there a way I can do time series calculation, such as a moving
>average in list comprehension syntax? I'm new to python but it looks
>like list comprehension's 'head' can only work at a value at a time. I
>also tried using the reduce function and passed in my list and another
>function which calculates a moving average outside the list comp. ...
>but I'm not clear how to do it. Any ideas? Thanks.
I used the following to return an array of the average of the last n
values -it's not particularly pretty, but it works
# set number of values to average
weighting = 10
# an array of values we want to calculate a running average on
ratings = []
# an array of running averages
running_avg = []
# some routine to fill ratings with the values
r = random.Random()
for i in range(0, 20):
ratings.append(float(r.randint(0, 99)))
for i in range(1, 1 + len(ratings)):
if i < weighting:
running_avg.append(ratings[i - 1])
else:
running_avg.append(reduce(lambda s, a: s+ a,
ratings[i - weighting : i]) /
len(ratings[i - weighting : i]))
for i in range(0, len(ratings)):
print "%3d: %3d %5.2f" % (i, ratings[i], running_avg[i])
sample output:
0: 34 34.00
1: 28 28.00
2: 58 58.00
3: 16 34.00
4: 74 44.00
5: 32 45.00
6: 74 49.00
7: 21 50.25
8: 78 51.25
9: 28 50.25
10: 32 39.75
11: 93 57.75
12: 2 38.75
13: 7 33.50
14: 8 27.50
15: 30 11.75
16: 1 11.50
17: 8 11.75
18: 40 19.75
19: 8 14.25
For all but the first 3 rows, the third column is the average of the
values in the 2nd column for this and the preceding 3 rows.
--
Jim Segrave (jes at jes-2.demon.nl)
More information about the Python-list
mailing list