我有两个 pandas 数据框 matches
与列(match_id
、team_id
、date
,...)和 teams_att
,其中包含列(id
、team_id
、date
、overall_ rating
、.. .)。
我想加入最接近 matches.date
matches.team_id =teams_att.team_id
和 teams_att.date
上的两个数据帧
示例
匹配
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
期望的结果
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
最佳答案
您可以将 merge_asof
与 by
和 direction
参数一起使用:
pd.merge_asof(matches.sort_values('date'),
teams_att.sort_values('date'),
on='date', by='team_id',
direction='nearest')
输出:
match_id team_id date id overall_rating
0 3 102 2010-05-21 7 42
1 1 101 2012-05-17 3 73
2 2 101 2014-07-11 5 74
3 4 102 2017-10-24 8 44
关于python-3.x - python Pandas 中的条件日期连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535205/