gpt4 book ai didi

python-3.x - Pandas 组合字符串行

转载 作者:行者123 更新时间:2023-12-04 09:05:23 25 4
gpt4 key购买 nike

我有一个像这样的 Pandas 数据帧:

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.
我需要一种方法来 当用户发送多条消息时合并消息 在另一个之前,同时保持原来的顺序。
期望的输出:
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.
Pandas 可以这样做吗?

最佳答案

尝试:

df = (df.groupby([df['User'].ne(df['User'].shift(1)).cumsum().values, 'User'])['Message']
.agg(' '.join).reset_index(level=1))

关于python-3.x - Pandas 组合字符串行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63460287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com