我有以下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几乎在那儿,但是我需要找到一种方法来迭代两列并将括号放在适当的位置。
答案 0 :(得分:1)
IIUC assign
和groupby
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