aabujamra
aabujamra

Reputation: 4636

Is there a way to groupby concatenating multiple strings?

I have the following df:

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

I want to turn it into:

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

I think the answer is somewhere in the groupby field, this question is almost there, however I need to find a way to do that iterating two columns and putting the parenthesis in place.

Upvotes: 0

Views: 40

Answers (1)

Umar.H
Umar.H

Reputation: 23099

IIUC assign and 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

Upvotes: 1

Related Questions