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))]
Here's a vectorized approach -
a.cumsum()/(np.arange(a.size)+1)
Please note that to make sure the results are floating pt numbers, we need to add in at the start :
from __future__ import division
Alternatively, we can use np.true_divide
for the division -
np.true_divide(a.cumsum(),(np.arange(a.size)+1))
Sample runs -
In [17]: a
Out[17]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
In [18]: a.cumsum()/(np.arange(a.size)+1)
Out[18]: array([ 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5])
In [20]: a
Out[20]: array([3, 3, 2, 4, 6, 6, 3, 5, 6, 4])
In [21]: a.cumsum()/(np.arange(a.size)+1)
Out[21]:
array([ 3. , 3. , 2.66666667, 3. , 3.6 ,
4. , 3.85714286, 4. , 4.22222222, 4.2 ])
From Pandas 0.18.0 out of the box, as you wanted :)
s = pd.Series([1, 2, 3, 4, 5])
s.rolling(5, min_periods=1).mean()
result is:
0 1.0
1 1.5
2 2.0
3 2.5
4 3.0
dtype: float64
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.