有没有一种方法可以通过串联多个字符串进行分组?

时间:2020-05-21 15:20:04

标签: python pandas pandas-groupby

我有以下df:

Name  Role     Company     [other columns]
John  Admin    GM
John  Director Kodak
John  Partner  McDonalds
Mark  Director Gerdau
Mark  Partner  Kibon

我想把它变成:

Name    Companies                                              [other columns]
John    GM (Admin), Kodak (Director), McDonalds (Partner)
Mark    Gerdau (Director), Kibon (Partner

我认为答案在groupby字段中的某个位置,this question几乎在那儿,但是我需要找到一种方法来迭代两列并将括号放在适当的位置。

1 个答案:

答案 0 :(得分:1)

IIUC assigngroupby

df1 = df.assign(companies=df['Company'] + ' (' + df['Role'] + ')')\
                                            .groupby('Name')['companies'].agg(','.join)

print(df1)

Name
John    GM (Admin),Kodak (Director),McDonalds (Partner)
Mark                  Gerdau (Director),Kibon (Partner)
Name: companies, dtype: object