rolling mean with increasing window
<p>I have a range</p>

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

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

<pre><code>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))
</code></pre>

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

<p>Here's a vectorized approach -</p>

<pre><code>a.cumsum()/(np.arange(a.size)+1)
</code></pre>

<p>Please note that to make sure the results are floating pt numbers, we need to add in at the start :</p>

<pre><code>from __future__ import division
</code></pre>

<p>Alternatively, we can use <code>np.true_divide</code> for the division -</p>

<pre><code>np.true_divide(a.cumsum(),(np.arange(a.size)+1))
</code></pre>

<p>Sample runs -</p>

<pre><code>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       ])
</code></pre>

python pandas numpy