title: Calculate the Mean of last 3 records in a timeseries data in pandas
body: <p>Facing problem in calculating the mean of last 3 records in my timeseries dataframe. Below is the sample of data</p>
  
  <pre><code>serial,date,feature1,,,,,,,,,,,,,,,,,
  1,5/19/2017,-5.199338,,,,,,,,,,,,,,,,,
  5,6/12/2017,-25.199338,,,,,,,,,,,,,,,,,
  5,6/23/2017,5.199338,,,,,,,,,,,,,,,,,
  2,7/1/2017,8.199338,,,,,,,,,,,,,,,,,
  1,7/17/2017,3.199338,,,,,,,,,,,,,,,,,
  1,7/29/2017,76.199338,,,,,,,,,,,,,,,,,
  2,8/19/2017,13.199338,,,,,,,,,,,,,,,,,
  6,9/19/2017,785.199338,,,,,,,,,,,,,,,,,
  3,10/28/2017,5.199338,,,,,,,,,,,,,,,,,
  4,11/2/2017,67.199338,,,,,,,,,,,,,,,,,
  2,11/28/2017,49.199338,,,,,,,,,,,,,,,,,
  2,12/29/2017,20.199338,,,,,,,,,,,,,,,,,
  3,1/29/2018,19.199338,,,,,,,,,,,,,,,,,
  4,3/13/2018,-15.199338,,,,,,,,,,,,,,,,,
  1,3/28/2018,-5.199338,,,,,,,,,,,,,,,,,
  </code></pre>
  
  <p>The requirement is to add another column say <code>mean</code> in dataframe, which will be the Mean value (for column <code>feature1</code>) of last 3 rows with similar <code>serial</code> numbers. This has to be done for every row.</p>
  
  <p>for example the calculation of mean for below row</p>
  
  <pre><code>1,3/28/2018,-5.199338,,,,,,,,,,,,,,,,,
  </code></pre>
  
  <p>will be done by using below dataset -</p>
  
  <pre><code>1,7/17/2017,3.199338,,,,,,,,,,,,,,,,,
  1,7/29/2017,76.199338,,,,,,,,,,,,,,,,,
  1,3/28/2018,-5.199338,,,,,,,,,,,,,,,,,
  </code></pre>
  
  <p>after calculating mean the row whould lo0k like</p>
  
  <pre><code>serial,date,feature1,mean_feature1,,,,,,,,,,,,,,,,,
  ...........................
  1,3/28/2018,-5.199338,24.7333,,,,,,,,,,,,,,,,
  </code></pre>
  
  <p>My problem statement is similar to below article but it is using rolling which requires definite window which is random in my case -
  <a href="https://stackoverflow.com/questions/36969174/pandas-average-value-for-the-past-n-days">Pandas: Average value for the past n days</a></p>
  
  <p>Expected Output -</p>
  
  <pre><code>serial,date,feature1,mean_feature1,,,,,,,,,,,,,,,,
  1,5/19/2017,-5.199338,-5.199338,,,,,,,,,,,,,,,,
  5,6/12/2017,-25.199338,-25.199338,,,,,,,,,,,,,,,,
  5,6/23/2017,5.199338,-10.0,,,,,,,,,,,,,,,,
  2,7/1/2017,8.199338,8.199338,,,,,,,,,,,,,,,,
  1,7/17/2017,3.199338,-1,,,,,,,,,,,,,,,,
  1,7/29/2017,76.199338,24.xxx,,,,,,,,,,,,,,,,
  2,8/19/2017,13.199338,10.7xx,,,,,,,,,,,,,,,,
  6,9/19/2017,785.199338,785.199338,,,,,,,,,,,,,,,,
  3,10/28/2017,5.199338,5.199338,,,,,,,,,,,,,,,,
  4,11/2/2017,67.199338,67.199338,,,,,,,,,,,,,,,,
  2,11/28/2017,49.199338,23.xxx,,,,,,,,,,,,,,,,
  2,12/29/2017,20.199338,27.xx,,,,,,,,,,,,,,,,
  3,1/29/2018,19.199338,12.xxx,,,,,,,,,,,,,,,,
  4,3/13/2018,-15.199338,26.xxxx,,,,,,,,,,,,,,,,
  1,3/28/2018,-5.199338,24.xxxxx,,,,,,,,,,,,,,,,
  </code></pre>
  
  <p>Please note values are approximately calculated for column 'mean_feature1`</p>