I am trying to calculate rolling average of goals scored by each team using Pandas in Python. My data looks like this:
league_round home_team_name away_team_name home_team_goals \
0 MLS Toronto FC Columbus Crew 0.0
1 MLS Houston Dynamo Atlanta United 4.0
2 MLS Philadelphia Union New England Revolution 2.0
3 MLS Orlando City DC United 1.0
4 MLS FC Dallas Real Salt Lake 1.0
away_team_goals
0 2.0
1 0.0
2 0.0
3 1.0
4 1.0
I tried following:
df_rolling = df.groupby('home_team_name')['home_team_goals'].rolling(window=3, min_periods=1).mean()
Output:
home_team_name
Atlanta United 17 3.000000
24 3.500000
46 4.000000
64 3.666667
77 3.666667
100 2.000000
124 1.666667
147 1.333333
177 1.666667
182 2.666667
218 2.000000
221 2.666667
247 2.000000
280 2.666667
330 2.333333
352 2.333333
374 2.000000
402 2.333333
404 2.666667
408 2.666667
Chicago Fire 14 3.000000
38 2.500000
Above code returns moving average for only specific home team when it plays at home. My question is how can lookup the team when it plays away and include it in my rolling average? and how can I paste the results to my original df? Thanks a lot