【问题标题】:Merge two dataframes iterating in within columns合并在列内迭代的两个数据框
【发布时间】:2019-05-14 13:32:37
【问题描述】:

我有两个数据框,一个是球员,有他们的俱乐部 ID 和回合,另一个有比赛,分数和回合。

播放器| club_id |圆形的
一个 | 16 | 1
乙 | 13 | 1
c | 12 | 1
一个 | 16 | 2
...

-------

home_club_id| away_club_id |home_club_score| away_club_score|圆形的
16 | 13 | 1 |2 |1
15 | 1 | 4 |0 |1
12 | 2 | 1 |1 |1
12 | 16 | 2 |2 |2
...

我想合并这两个数据框,看看是否有球员在家踢球,以及比赛的比分。
最终的数据框可能是这样的:

球员|club_id|round|home|score|opponent_score
一个 |16 |1 |是|1 | 2
b |13 |1 |没有 |2 | 1
一个 |16 |2 |没有 |2 | 2
...

我尝试将 home_club_id 更改为 club_id 并与 on =[round, club_id] 合并,但我没有找到同时合并 home 和 away 的方法

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    要获得所需的最终帧,您可以重新排列数据。

    首先,假设您的帧被称为player_frameround_frame

    from io import StringIO
    
    import pandas as pd
    
    player_data = StringIO('''Player club_id  round  
    a          16     1
    b          13     1
    c          12     1
    a          16     2''')
    player_frame = pd.read_csv(player_data, sep='\s+')
    
    round_data = StringIO('''home_club_id away_club_id home_club_score away_club_score round  
    16               13          1           2               1
    15               1           4           0               1
    12               2           1           1               1
    12               16          2           2               2''')
    round_frame = pd.read_csv(round_data, sep='\s+')
    

    然后我们可以拉出列来分别引用主场和客场数据,重命名以使它们匹配,并标记该行是否是主场比赛。

    home_values = round_frame[['home_club_id', 'home_club_score', 'away_club_score', 'round']]\
                             .rename({'home_club_id': 'club_id', 
                                      'home_club_score': 'score', 
                                      'away_club_score': 'opponent_score'},
                                     axis=1)\
                             .assign(home='yes')
    
    away_values = round_frame[['away_club_id', 'away_club_score', 'home_club_score', 'round']]\
                             .rename({'away_club_id': 'club_id', 
                                      'home_club_score': 'opponent_score', 
                                      'away_club_score': 'score'},
                                     axis=1)\
                             .assign(home='no')
    

    那么我们可以concat两者合并成player_frame

    final_values = pd.concat([home_values, away_values], ignore_index=True).merge(player_frame)
    

    这给了我们:

       club_id  score  opponent_score  round home Player
    0       16      1               2      1  yes      a
    1       12      1               1      1  yes      c
    2       13      2               1      1   no      b
    3       16      2               2      2   no      a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      相关资源
      最近更新 更多