Moving average by id/group with a defined interval in python
<p>Given is a csv dataset with the following columns and values (example).
I want to <strong>add a new column</strong> in my csv data with a <strong>moving average</strong> of S1 according to each id. S1 are my measurements. The timeframe t should be 3.That's how my dataset currently looks.</p>

<pre><code>id  S1  
1   3
1   4
1   2
1   6
1   9
2   3
2   1
2   2
2   3
2   8
2   6
3   1
3   4
3   2
3   8
3   5
</code></pre>

<p>And that's what I wanna do:</p>

<pre><code>id  S1   movA  
1   3    NaN
1   4    NaN
1   2    3.000
1   6    4.000
1   9    5.667
2   3    NaN
2   1    NaN
2   2    2.000
2   3    2.000
2   8    4.333
2   6    5.333
3   1    NaN
3   4    NaN
3   2    2.333
3   8    4.667
3   5    5.000
</code></pre>

<p>use <code>groupby</code> and <code>rolling</code> with <code>mean</code></p>

<pre><code>g = df.groupby('id').S1
rolls = [2, 3, 4, 5]
pd.concat([g.rolling(i).mean() for i in rolls], axis=1, keys=rolls)
</code></pre>

<p><a href="http://i.stack.imgur.com/2veRn.png" rel="nofollow"><img src="http://i.stack.imgur.com/2veRn.png" alt="enter image description here"></a></p>

python csv pandas numpy moving-average