Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rolling mean with increasing window

I have a range

np.arange(1,11) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and for each element, i, in my range I want to compute the average from element i=0 to my current element. the result would be something like:

array([ 1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ,  5.5])
 # got this result via np.cumsum(np.arange(1,11,dtype=np.float32))/(np.arange(1, 11))

I was wondering if there isn't an out of the box function in numpy / pandas that gives me this result?

like image 844
Vincent Claes Avatar asked Dec 25 '22 01:12

Vincent Claes


2 Answers

You can use expanding() (requires pandas 0.18.0):

ser = pd.Series(np.arange(1, 11))

ser.expanding().mean()
Out: 
0    1.0
1    1.5
2    2.0
3    2.5
4    3.0
5    3.5
6    4.0
7    4.5
8    5.0
9    5.5
dtype: float64
like image 85
ayhan Avatar answered Dec 26 '22 13:12

ayhan


This seems to be the simplest, although it may become inefficient if x is very large:

x = range(1,11)
[np.mean(x[:i+1]) for i in xrange(0,len(x))]
like image 28
mgalle Avatar answered Dec 26 '22 14:12

mgalle