I have a DataFrame similar to the below:, and I want to add a Streak column to it (see example below):
Date Home_Team Away_Team Winner Streak
2005-08-06 A G A 0
2005-08-06 B H H 0
2005-08-06 C I C 0
2005-08-06 D J J 0
2005-08-06 E K K 0
2005-08-06 F L F 0
2005-08-13 A B A 1
2005-08-13 C D D 1
2005-08-13 E F F 0
2005-08-13 G H H 0
2005-08-13 I J J 0
2005-08-13 K L K 1
2005-08-20 B C B 0
2005-08-20 A D A 2
2005-08-20 G K K 0
2005-08-20 I E E 0
2005-08-20 F H F 2
2005-08-20 J L J 2
2005-08-27 A H A 3
2005-08-27 B F B 1
2005-08-27 J C C 3
2005-08-27 D E D 0
2005-08-27 I K K 0
2005-08-27 L G G 0
2005-09-05 B A A 2
2005-09-05 D C D 1
2005-09-05 F E F 0
2005-09-05 H G H 0
2005-09-05 J I I 0
2005-09-05 K L K 4
The DataFrame is approximately 200k rows going from 2005 to 2020.
Now, what I am trying to do is find the number of consecutive games the Home Team has won PRIOR to the date in in the Date column in the DataFrame. I have a solution, but it is too slow, see below:
df["Streak"] = 0
def home_streak(x): # x is a row of the DataFrame
"""Keep track of a team's winstreak"""
home_team = x["Home_Team"]
date = x["Date"]
# all previous matches for the home team
home_df = df[(df["Home_Team"] == home_team) | (df["Away_Team"] == home_team)]
home_df = home_df[home_df["Date"] < date].sort_values(by="Date", ascending=False).reset_index()
if len(home_df.index) == 0: # no previous matches for that team, so start streak at 0
return 0
elif home_df.iloc[0]["Winner"] != home_team: # lost the last match
return 0
else: # they won the last game
winners = home_df["Winner"]
streak = 0
for i in winners.index:
if home_df.iloc[i]["Winner"] == home_team:
streak += 1
else: # they lost, return the streak
return streak
df["Streak"] = df.apply(lambda x: home_streak(x), axis = 1)
How can I speed this up?
A
wins as an away team? What if it loses? Does that continue/end the streak? Or does the info get lost?