Need to calculate each participating team's average goals per game (rolling_avg
) up to a point in time. Since my database is highly normalized, this takes quite a lot of time (+8k rows)
Notes:
I'm counting the total goals (column 0) scored in a match, not each team's goals.
There are additional columns that are omitted here but could be relevant: one of them is a
date_time
column.
Example: in row #1 (the second row) we can see the first game of team 1249
(they're playing away). In this game, 3 goals were recorded. The next game of team 1249
takes place in row #10, and since that team is playing at home this time (as its id
appears under home_team_id
), I want the home_rolling_avg
to be equal 3. It shouldn't take into account the current row.
Question:
How do I calculate each team's goals expanding average/mean, based on previous values in total_goals
and excluding the current row, and assign this mean value to the relevant column (depends on whether the team is playing at home or away)?
total_goals home_team_id away_team_id home_goals away_goals home_rolling_avg away_rolling_avg
0 2 1277 1241 1 1 NaN NaN
1 3 1245 1249 2 1 NaN NaN
2 1 1242 1246 0 1 NaN NaN
3 4 1261 1248 1 3 NaN NaN
4 2 1259 1240 2 0 NaN NaN
5 3 2981 1268 1 2 NaN NaN
6 1 1244 1255 1 0 NaN NaN
7 1 1254 1276 1 0 NaN NaN
8 7 1247 12140 5 2 NaN NaN
9 3 5681 1270 2 1 NaN NaN
10 1 1249 5681 0 1 NaN NaN
# in line 10 above, 'home_rolling_avg' should show 3 (3/1)
Update:
a larger sample (n=100) can be found here. Added due a request by the kind piRSquared (answer here).