Categories
Python Answers

How to concatenate strings from several rows using Python Pandas groupby?

Spread the love

To concatenate strings from several rows using Python Pandas groupby, we can use the transform method.

For instance, we write

df['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))
df[['name','text','month']].drop_duplicates()

to create the text column that calls groupby on the selected columns name and month.

And then we get the text column from the grouped data frame and call transform with a lamnda function to join the strings together.

And then we call drop_duplicates to drop the duplicate rows.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *