【问题标题】:Conditional date join in python Pandaspython Pandas中的条件日期加入
【发布时间】:2018-05-12 02:59:13
【问题描述】:

我有两个熊猫数据框matches,带有列(match_idteam_iddate,...)和teams_att,带有列(idteam_iddate,@ 987654329@, ...)。 我想加入最接近matches.datematches.team_id = teams_att.team_idteams_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

【问题讨论】:

    标签: python-3.x pandas join


    【解决方案1】:

    我们使用merge_asof (Please check Scott's answer, that is the right way for solving this type problem :-) cheers)

    g1=df1.groupby('team_id')
    g=df.groupby('team_id')
    
    l=[]
    for x in [101,102]:
       l.append(pd.merge_asof(g.get_group(x),g1.get_group(x),on='date',direction ='nearest'))
    
    
    pd.concat(l)
    Out[405]: 
       match_id  team_id_x       date  id  team_id_y  overall_rating
    0         1        101 2012-05-17   3        101              73
    1         2        101 2014-07-11   5        101              74
    0         3        102 2010-05-21   7        102              42
    1         4        102 2017-10-24   8        102              44
    

    【讨论】:

      【解决方案2】:

      您可以将merge_asofbydirection 参数一起使用:

      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
      

      【讨论】:

      • 这很酷,我不知道,我们这里有by.. 学习一下,谢谢 :-)
      • @Wen 好吧,我已经回报了你为我做的许多人情之一。
      • @ScottBoston 如果两个数据框的键列名称不同[给'by'的那个]
      • @IsmailKarchi 有参数left_onright_onleft_byright_bypd.merge_asof
      猜你喜欢
      • 2018-12-11
      • 1970-01-01
      • 2016-12-09
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多