title: Pandas, how to calculate mean values of the past n years for every month
body: <p>I have a dataframe with data for 20 years with the time as datatime index.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p><code>Time               value<br>
  1999-01-01 00:00:00  7
  1999-01-01 01:00:00  4
  1999-01-01 02:00:00  9
  1999-01-01 03:00:00  4
  1999-01-01 04:00:00  2
                         ...
  2018-12-31 19:00:00  8
  2018-12-31 20:00:00  1
  2018-12-31 21:00:00  9
  2018-12-31 22:00:00  6
  2018-12-31 23:00:00  5</code></p>
  
  <p>I needed to get the sum for every month, which I did like</p>
  
  <pre><code>df_new = df.groupby([df.index.year, df.index.month]).sum()
  </code></pre>
  
  <p>And the result</p>
  
  <pre><code>     Month  value
  1999    1   6
          2   9
          3   7
  2000    1   5
          2   7
          3   6
  2001    1   4
          2   6
          3   8
  2002    1   7
          2   9
          3   8
  2003    1   5
          2   7
          3   7
          ....
  2018    1   9
          2   6
          3   7
  </code></pre>
  
  <p>But now I need a way to calculate the average for the past 3 years for every month. For example for 2002 I will have: for month 1 the average of month 1 of 1999,2000,2001, for month 2 the average of month 2 of 1999,2000,2001 and so on. Then for 2003 the average will be for 2000, 2001 and 2002 and like that until 2018. Meaning the first 3 years I will get Nan values.</p>
  
  <p>So my final output should look like this:</p>
  
  <pre><code>   Month    value   average_past_3_years
  1999    1   6   nan
          2   9   nan
          3   7   nan
  2000    1   5   nan
          2   7   nan
          3   6   nan
  2001    1   4   nan
          2   6   nan
          3   8   nan
  2002    1   7   5.0
          2   9   7.3
          3   8   7.0
  2003    1   5   5.3
          2   7   7.3
          3   7   7.3
              ...
  </code></pre>
  
  <p>I was thinking to use .apply() but can not figure it out a function to make it work :(</p>
  
  <pre><code>df.groupby([df.index.year, df.index.month]).apply(somefunction)
  </code></pre>