title: Is there a way to calculate yearly moving average in Python?
body: <p>I have some football data that I am modifying for analysis. I basically want to calculate career and yearly per game averages on a weekly basis for several stats.</p>
  <p><strong>Example</strong></p>
  <p>What I have:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>Player</th>
  <th>Year</th>
  <th>Week</th>
  <th>Rushing Yards</th>
  <th>Catches</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>Seth Johnson</td>
  <td>2020</td>
  <td>1</td>
  <td>100</td>
  <td>4</td>
  </tr>
  <tr>
  <td>Seth Johnson</td>
  <td>2020</td>
  <td>2</td>
  <td>80</td>
  <td>2</td>
  </tr>
  <tr>
  <td>Seth Johnson</td>
  <td>2021</td>
  <td>1</td>
  <td>50</td>
  <td>3</td>
  </tr>
  <tr>
  <td>Seth Johnson</td>
  <td>2021</td>
  <td>2</td>
  <td>50</td>
  <td>2</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>What I want:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>Player</th>
  <th>Year</th>
  <th>Week</th>
  <th>Rushing Yards</th>
  <th>Catches</th>
  <th>Career Rushing Yards per Game</th>
  <th>Career Catches per Game</th>
  <th>Yearly Rushing Yards per Game</th>
  <th>Yearly Catches per Game</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>Seth Johnson</td>
  <td>2020</td>
  <td>1</td>
  <td>100</td>
  <td>4</td>
  <td>100</td>
  <td>4</td>
  <td>100</td>
  <td>4</td>
  </tr>
  <tr>
  <td>Seth Johnson</td>
  <td>2020</td>
  <td>2</td>
  <td>80</td>
  <td>2</td>
  <td>90</td>
  <td>3</td>
  <td>90</td>
  <td>3</td>
  </tr>
  <tr>
  <td>Seth Johnson</td>
  <td>2021</td>
  <td>1</td>
  <td>50</td>
  <td>3</td>
  <td>76.67</td>
  <td>3</td>
  <td>50</td>
  <td>3</td>
  </tr>
  <tr>
  <td>Seth Johnson</td>
  <td>2021</td>
  <td>2</td>
  <td>40</td>
  <td>2</td>
  <td>67.5</td>
  <td>2.75</td>
  <td>45</td>
  <td>2.5</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I figure I could calculate the Career stats and Yearly stats separately then just join everything on Player/Year/Week, but I'm not sure how to go about calculating the moving averages given that the window would be dependant on Year and Week.</p>
  <p>I've tried things like looping through the desired categories and calculating rolling averages:</p>
  <p><code>new_df['Career ' + category + ' per Game'] = df.groupby('Player')[category].apply(lambda x: x.rolling(3, min_periods=0).mean())</code></p>
  <p>But I'm not finding the creativity necessary to make the appropriate custom window for rolling(). Does anyone have any ideas here?</p>