A running average is just, for each value in a list, the average of all of the values up to that one. For a stripped-down version of your example:
>>> tData = [86,87,84,86]
The running averages are 86/1
, (86+87)/2
, (86+87+84)/3
, and (86+87+84+86)/4
.
So, at each index, the running average is the running total, dividing by (index + 1).
You can get the running totals with accumulate
:
>>> list(accumulate(tData))
[86, 173, 257, 343]
And you can get the (1-based) indexes with enumerate
:
>>> list(enumerate(accumulate(tData, start=1))
[(1, 86), (2, 73), (3, 257), (4, 343)]
So, just divide:
>>> [total / index for index, total in enumerate(accumulate(tData, start=1))]
[86.0, 86.5, 85.66666666666667, 85.75]
Or using statistics
in Python 3.4, or its backport/predecessor stats
for 3.1-3.3:
>>> from stats import running_average
>>> running_average(tData)
[86, 86.5, 85.66666666666667, 85.75]
Of course you can always do it explicitly if you prefer:
>>> running_sum, running_sums = 0, []
>>> for value in tData:
... running_sum += value
... running_sum.append(running_sum)
>>> [value / index for index, value in enumerate(running_sums, start=1)]
[86, 86.5, 85.66666666666667, 85.75]
… or even:
>>> running_sum, running_averages = 0, []
>>> for index, value in enumerate(tData, start=1):
... running_sum += value
... running_averages.append(running_sum / index)
>>> running_averages
[86, 86.5, 85.66666666666667, 85.75]