Question Details

No question body available.

Tags

python pandas machine-learning

Answers (2)

Accepted Answer Available
Accepted Answer
May 8, 2026 Score: 4 Rep: 767 Quality: High Completeness: 70%

shift(1).rolling(5).mean() is correct but you are applying it across the entire dataframe which may mix different teams. You should group by team first.

The NaN issue reason- if a team has only played 2 games, there genuinely is no 5-game average yet.

Group by Team First-

import pandas as pd

df = pd.readcsv("D1.csv") df = df.sortvalues(["HomeTeam", "Date"]) #miantain chronological order

n = 5

df["avggoalslast5"] = ( df.groupby("HomeTeam")["FTHG"] .transform(lambda x: x.shift(1).rolling(n, minperiods=1).mean()) )

  • groupby("HomeTeam") ensures rolling only looks within the same team's history

  • shift(1) excludes the current game's goals from its own average

  • minperiods=1 allows partial averages for early games instead of dropping them entirely

May 8, 2026 Score: 1 Rep: 1 Quality: Low Completeness: 50%

df["FTHG"].shift(1).rolling(5).mean()

This drop an NaN cause the first match has no previous match so you should group by team first and do a shift rolling from then

df = df.sortvalues(["HomeTeam", "Date"])

df["goals"] = ( df.groupby("HomeTeam")["FTHG"] .shift(1) .rolling(5, min
periods=1) .mean() .reset_index(level=0, drop=True) )