title: Pandas Combine Multiple Specific Previous Rows
body: <p>I wasn't 100% sure how to word the question title as its quite a specific thing I am asking. I have simplified the question into the core relevant components and made up some dataframes to demonstrate what I am after.</p>
  
  <p>I have data of the form:</p>
  
  <p><a href="https://i.stack.imgur.com/vj8w1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vj8w1.png" alt="original data"></a></p>
  
  <p>I am trying to run some prediction algorithm on this data and want it in the form:</p>
  
  <p><a href="https://i.stack.imgur.com/zuX4U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zuX4U.png" alt="enter image description here"></a></p>
  
  <p>Where the stats of a player_id and game_id are taken as combinations of the previous n (n=2 in this example) game_ids stats of that player.</p>
  
  <p>For example for player_id = 1 and game_id = 3 the stats are set to the sum of their corresponding values in game_id = 2 and game_id = 1. I also want players with missing game_id stats to be handled as all stats = 0 for the missing game_id (as in player_id = 2, game_id = 3 and 4).</p>
  
  <p>I was thinking of creating a new dataset with rows for each player_id and each game_id combination as indexes (starting from game_id = n + 1 as you need at least n prior games number of stats) and then copying over values from the previous dataset using some sort of concatenation or join (taken from <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html</a>) but I am unsure of the best way to do this with n rows needed to be concatenated based of the player_id and game_id.</p>
  
  <p>Any help or suggestions is much appriated!</p>