2

I have a pandas DataFrame like this:

Index   User    Message
1       User1   This is
2       User1   a test.
3       User2   The test
4       User2   is received.
5       User1   This is a complete sentence.
6       User2   This is another complete sentence.
7       User1   Finished.

I need a way to combine the messages when a user sends more than one message before the other while keeping the original order.

Desired output:

Index   User    Message
1       User1   This is a test.
2       User2   The test is received
3       User1   This is a complete sentence.
4       User2   This is another complete sentence.
5       User1   Finished.

Is this possible with pandas?

1 Answer 1

2

Try:

df = (df.groupby([df['User'].ne(df['User'].shift(1)).cumsum().values, 'User'])['Message']
        .agg(' '.join).reset_index(level=1))
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I needed. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.