首页 > 解决方案 > 来自具有不同列名和行大小但几乎没有重合值的两个数据帧的结果数据帧,并行呈现(Python)

问题描述

有两个数据框,其中包含玩家 ID 和他们在两天的锦标赛(周一和周五)中获得的所有积分。我想得到一个具有以下格式的最终​​数据框。

    final =
       match_monday    points      match_friday     points   
    0  player#0005     13.0        player#0005      19.0
    1  player#0067     26.0        player#0067      0.0
    2  player#0098     0.0         player#0098      23.0  
    4  player#0104     24.0        player#0104      0.0
    5  player#0211     14.0        player#0211      0.0 
    6  player#0227     17.0        player#0227      21.0    

起点是这两个数据框:

    df1 =  
       match_monday     points           
    0  player#0227      17.0  
    1  player#0005      13.0  
    2  player#0104      24.0  
    3  player#0067      26.0  
    4  player#0211      14.0  

    df2 =  
       match_friday     points           
    0  player#0227      21.0  
    1  player#0098      23.0  
    2  player#0005      19.0  


    #Dataframes scripts:
    df1 = pd.DataFrame([['player#0227',17.0],['player#0005',13.0],['player#0104',24.0],['player#0067',26.0],['player#0211',14.0]],columns=['match_monday','points'])
    df2 = pd.DataFrame([['player#0227',21.0],['player#0098',23.0],['player#0005',19.0]],columns=['match_friday','points']) 

我已经合并了这两个数据框,并意识到从这里开始我需要很多步骤才能达到所需的格式。合并结果:

        match_monday  points match_friday
    0  player#0227    17.0          NaN
    1  player#0005    13.0          NaN
    2  player#0104    24.0          NaN
    3  player#0067    26.0          NaN
    4  player#0211    14.0          NaN
    5          NaN    21.0  player#0227
    6          NaN    23.0  player#0098
    7          NaN    19.0  player#0005

当我意识到我的方法不是那么好时,我试图用这句话命令 match_friday 放入一个“for循环”。

    matchMon = df2[df2.match_friday.isin(df1.match_monday)]

    print(machMon)
    match_friday  points
    0  player#0227    21.0
    2  player#0005    19.0

标签: python-3.xpandas

解决方案


我认为更好的是使用不同的方法 -Series通过DataFrame.set_indexwith创建concat并最后替换缺失值fillna- 然后获取所有玩家的索引:

a = df1.set_index('match_monday')['points'].rename('po_mon')
b = df2.set_index('match_friday')['points'].rename('po_fri')

df = pd.concat([a, b], axis=1, sort=False).fillna(0)
print (df)
             po_mon  po_fri
player#0227    17.0    21.0
player#0005    13.0    19.0
player#0104    24.0     0.0
player#0067    26.0     0.0
player#0211    14.0     0.0
player#0098     0.0    23.0

推荐阅读