Conditional date join in python Pandas

Viewed 70

I have two pandas dataframes matches with columns (match_id, team_id,date, ...) and teams_att with columns (id, team_id, date, overall_rating, ...). I want to join the two dataframes on matches.team_id = teams_att.team_id and teams_att.date closest to matches.date

Example

matches

match_id    team_id     date
1           101         2012-05-17
2           101         2014-07-11
3           102         2010-05-21
4           102         2017-10-24

teams_att

id  team_id     date        overall_rating
1   101         2010-02-22  67
2   101         2011-02-22  69
3   101         2012-02-20  73
4   101         2013-09-17  79
5   101         2014-09-10  74
6   101         2015-08-30  82
7   102         2015-03-21  42
8   102         2016-03-22  44

Desired results

match_id    team_id     matches.date    teams_att.date      overall_rating
1           101         2012-05-17      2012-02-20          73
2           101         2014-07-11      2014-09-10          74
3           102         2010-05-21      2015-03-21          42
4           102         2017-10-24      2016-03-22          44
2 Answers
Related