如何在Python Pandas中合并两个复杂的数据框?

4

我有两个pandas数据框。

dictionary1 = {'match_up' : ['1985_1116_1234' , '1985_1116_1475', '1985_1234_1172', '1985_1475_2132',  '1985_1242_1325'], \
               'result': [1, 1, 0, 0, 1], 'year':[1985,1985,1985,1985,1985]  }


dictionary2 = {'team' : [1234 , 1475,  2132, 1172, 1242, 1116 , 1325], 'win_A_B': [0.667, 0.636, 0.621, 0.629, 0.615,0.943, 0.763], \
               'year':[1985,1985,1985,1985,1985,1985,1985] }

df1 = pd.DataFrame(dictionary1)

df2 = pd.DataFrame(dictionary2)

df1:
           match_up     result  year
    0   1985_1116_1234    1     1985
    1   1985_1116_1475    1     1985
    2   1985_1234_1172    0     1985
    3   1985_1475_2132    0     1985
    4   1985_1242_1325    1     1985

df2:
    team      win_A_B    year
    1234      0.667      1985
    1475      0.636      1985 
    2132      0.621      1985
    1172      0.629      1985
    1242      0.615      1985
    1116      0.943      1985
    1325      0.763      1985

数据框df1中的列值与数据框df2中的列team相匹配。数据框df2中的列team的值都是唯一的。

我需要按以下方式组合上述两个数据框:

           match_up     result  year   team_A   team_B    win_A    win_B
    0   1985_1116_1234    1     1985    1116      1234     0.943    0.667    
    1   1985_1116_1475    1     1985    1116       1475    0.943     0.636
    2   1985_1234_1172    0     1985    1234       1172    0.667     0.629
    3   1985_1475_2132    0     1985    1475       2132    0.636    0.621
    4   1985_1242_1325    1     1985    1242       1325    0.615    0.763

我知道我之前在pandas中已经问过类似的问题。我是pandas的新手,如果我问了一些这样的问题,请您耐心等待。


1
如果您能以易于导入的形式提供数据,那将非常有帮助。 - cge
@cge 好的,让我修改一下我的问题。 - MJP
@cge 我已经编辑了这个问题。 - MJP
1个回答

2
以下内容可行:
d_teams=pd.DataFrame( [[int(y) for y in x.split('_')[1:]] \
            for x in df1.match_up], columns=('team_A', 'team_B') )
merged=pd.concat((df1,d_teams),axis=1)
df2i=df2.set_index('team')
merged['win_A']=df2i.ix[merged.team_A].reset_index().win_A_B
merged['win_B']=df2i.ix[merged.team_B].reset_index().win_A_B

首先,我们创建一个名为d_teams的DataFrame,它由match_up列组成,通过“_”拆分并转换为int类型。我们丢弃年份,因为它已经包含在df1中,只保留team_A和team_B。然后,我们通过将其与df1连接来创建一个合并的数据框。
接下来,我们创建一个名为df2i的按团队索引的df2。然后,我们可以使用merged.team_A或merged.team_B进行索引以获取胜利值。但是,我们不希望结果按这些团队进行索引,因此我们首先重置索引。

你能解释一下这个命令 merged['win_A']=df2i.ix[merged.team_A].reset_index().win_A_B 吗? - MJP
1
merged.team_Amergedteam_A 值的列表。由于我们已经将团队值设置为 df2i 的索引,因此 df2i.ix [merged.team_A] 给出了与 team_A 值对应的 df2i 行的 DataFrame。然后我们使用 reset_index() 删除团队索引,并从该 DataFrame 中选择 win_A_B 列。然后我们将其分配给 merged 中的 win_A 列。 - cge
是的,我明白了。讲解太棒了!! - MJP
一个简单的查询 ->[[int(y) for y in x.split('_')[1:]] for x in df1.match_up] 给出了以下输出: [[1116,1234],[1116,1475],[1234,1172],[1475,2132],[1242,1325]]。现在,通过传递 d_teams=pd.DataFrame( [[int(y) for y in x.split('_')[1:]] \ for x in df1.match_up], columns=('team_A', 'team_B'),将内部列表中的第一个值分配为第一列,并将第二个值分配为第二列。在字典中,我知道键成为我的列,值成为我的行。这个列表中的列表是否有类似的概念? - MJP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接