I need to groubpy/aggregate with adding a comma

Issue

I want to aggregate in this data frame columns.

data = {'one':['one', 'five', 'one', 'one'],
        'two':['one', 'five', 'one', 'one']}
df = pd.DataFrame(data)
df

Using the following code:

new_df = df.groupby('one').agg(names = ('two', 'sum'))

The output will be:

five    five
one     oneoneone

How to add a comma between the aggregated results?

The wanted result:

five    five
one     one, one, one

Solution

You just need to add ','.join instead of sum.

 new_df = df.groupby('one').agg(names = ('two', ', '.join))

Output:

             names
one 
five          five
one   one, one, one

Answered By – Rajan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published