abutremutante abutremutante - 3 years ago 100
Python Question

Python / Pandas - Merge columns with the same index in a single cell

I have this dataframe:

Dude
group_id
820125 ARMANDO
820125 LUIS OSWALDO
64907 BERNARDO
64907 SANDRO
64907 VERONICA


I want it to look like this:

Dudes
group_id
820125 ARMANDO | LUIS OSWALDO
64907 BERNARDO | SANDRO | VERONICA


Already tried variations of merge, join and concat but wasn't successful. Any idea?

Answer Source

You can group by index and join the column:

df.groupby(level=0).agg(' | '.join)
#                                   Dude
#group_id   
#64907      BERNARDO | SANDRO | VERONICA
#820125           ARMANDO | LUIS OSWALDO

To join a specific column only, use a dictionary in the agg function:

df.groupby(level=0).agg({"Dude": ' | '.join})

Same output as above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download