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?
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
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))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With