代码之家  ›  专栏  ›  技术社区  ›  8-Bit Borges

Pandas-将值从一列映射到新列

  •  0
  • 8-Bit Borges  · 技术社区  · 4 年前

    我有一个数据框架,包含所有个人团队的比赛,其中一些比赛是重复的,就像这样:

    team        adversary     xG
    Liverpool   City          1.80
    ...
    City        Liverpool     1.21
    ...
    

    我如何跟踪所有团队对手对的xG值,最终得到:

    team        adversary     xG_team    xG_adversary
    Liverpool   City          1.80       1.21
    ...
    City        Liverpool     1.21       1.80
    ...
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   wjandrea sebs    4 年前

    你可以进行自我合并。我认为最简单的方法是 set_index 在右边df:

    df.merge(
        df.set_index(['adversary', 'team']),
        left_on=['team', 'adversary'],
        right_index=True,
        suffixes=('_team', '_adversary'),
        how='left')
    

    后果

            team  adversary  xG_team  xG_adversary
    0  Liverpool       City     1.80          1.21
    1       City  Liverpool     1.21          1.80