代码之家  ›  专栏  ›  技术社区  ›  Nick

如何在Python中使用Pandas将具有相同唯一ID的多行合并为一行[重复]

  •  0
  • Nick  · 技术社区  · 1 年前

    我见过一些类似的问题,但我找不到一个解决如何拆包多列的问题。我使用成功地拆下了一列。

    df = df.groupby(['id', 'entity'])['true_value'].aggregate('first').unstack(sort=True)
    

    然而,我想把这个

    id entity     true_value         extracted_value    rater  ratio
    1  student    no                 yes                FALSE  100
    1  address    303 lake way       303 lake way       TRUE   100
    1  email      [email protected]     [email protected]  FALSE  0
    2  student    yes                yes                TRUE   100
    2  address    15 putin ave       15 putnam ave      FALSE  0
    2  email      [email protected]     [email protected]     TRUE   95
    

    进入这个

    id student_true   student_extracted  student_rater  student_ratio  address_true       address_extracted  address_rater  address_ratio  email_true         email_extracted     email_rater     email_ratio
    1  no             yes                FALSE          100            303 lake way       303 lake way       TRUE           100            [email protected]     [email protected]   FALSE           0
    2  yes            yes                TRUE           100            15 e putnam ave    15 putnam ave      FALSE          0              [email protected]     [email protected]      TRUE            95
    

    任何帮助都将不胜感激。谢谢!

    我尝试过以许多不同的方式使用groupby和unstack来获得预期的结果,但都失败了。

    1 回复  |  直到 1 年前
        1
  •  1
  •   e-motta    1 年前

    pivot 然后重命名列:

    out = df.pivot(index="id", columns="entity").reset_index()
    out.columns = [f"{col[1]}_{col[0]}".replace("_value", "") for col in out.columns]
    
       _id  address_true      email_true student_true address_extracted  ... email_rater student_rater  address_ratio  email_ratio  student_ratio
    0    1  303 lake way  [email protected]           no      303 lake way  ...       False         False            100            0            100
    1    2  15 putin ave  [email protected]          yes     15 putnam ave  ...        True          True              0           95            100
    
    [2 rows x 13 columns]