I have two DataFrames, One contains different dates and different player_id. The second one contains the history of each player's rating, which means it contains different dates and different player_id and player_rating with a unique id of each row.
Now, I want to add a column to the first DataFrame with the one value of the player_rating by comparing the date columns in the two DataFrames.
For example:
print(df_1)
date player_id
0 2006 1
1 2006 2
2 2012 3
3 2008 2
4 2010 1
print(df_2)
date player_id player_rating
0 2005 1 50
1 2007 2 55
2 2005 3 70
3 2005 2 65
4 2009 1 60
5 2011 2 75
6 2011 3 85
Here, I should compare the first row in df_1 with the first and fifth rows in df_2 (the same player_id) then choose the row from df_2 with the most updated date and smaller than the date in df_1. So, I should choose the first row and set the player_rating to 50.
Finally, I should get:
print(df_1)
date player_id player_rating
0 2006 1 50
1 2006 2 65
2 2012 3 85
3 2008 2 55
4 2010 1 60
I have tried many solutions and get the following idea but it takes much time to run relative to a huge dataset (about one million rows of df_1 and +100k rows of df_2):
def get_rating(date, player_id):
return df_2[(df_2['player_id']==player_id) & (df_2['date'] < date)].sort_values(by=['date'], ascending=False).player_rating.iloc[0]
df_1['player_rating'] = [get_rating(x,y) for x, y in zip(df_1['date'], df_1['player_id'])]
If there is a better way to save some time here? Thank you in advance.