python - 根据列值对有序 Pandas 数据框中的行进行分组

标签 python python-3.x pandas

我有一个问题,即根据它们的列值,将 pandas 数据框中的某些行(按时间戳排序)仅组合在一起。

举个例子:

df=pd.DataFrame({"text":["Hello.",
                    "I had a question.", 
                    "Hi!",
                    "Yes how can I help?",
                    "Do you ship to the UK?"
                    ],
            "timestamp":[
                        pd.Timestamp('20131213 11:50:00'),
                        pd.Timestamp('20131213 11:51:00'),
                        pd.Timestamp('20131213 11:52:00'),
                        pd.Timestamp('20131213 11:53:00'),
                        pd.Timestamp('20131213 11:54:00')
                        ],
            "direction":["In","In","Out","Out","In"]})

这是数据框的样子:

enter image description here

此数据帧按时间戳排序,可以是(例如)聊天线程,其中方向“In”可能是一个人在说话,“Out”是另一个人在说话。

我想得到的是这样的: enter image description here

在最终的数据框中,如果行的文本方向相同,则这些行的文本被组合到一行中,但行只会组合在一起,直到您到达具有不同方向的行。 并且保留消息的顺序。

有没有人有什么想法?

最佳答案

设置

operations = {
    'text': ' '.join,
    'direction': 'first',
}

使用 agg 和按连续值分组的常用技巧:

df.groupby(df.direction.ne(df.direction.shift()).cumsum()).agg(operations)

                               text direction
direction
1          Hello. I had a question.        In
2           Hi! Yes how can I help?       Out
3            Do you ship to the UK?        In

关于python - 根据列值对有序 Pandas 数据框中的行进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52783162/

相关文章:

python - 如何在 DateTimeIndex 中选择唯一日期的行

python - Pandas 拆解专栏

python - 假设 unicode_literals,如何安全地评估文字的表示?

python - 转换从 fetchall() 返回的类型

python - 如何返回一个值,但继续执行

python - ttk 标签不正常

python-3.x - Pygame - 使用转义字符或换行符对文本进行 blitting

python - 如何使用 tkinter 打开 .gif 文件而不出现错误 "Too early to create image"?

python - 属性错误: 'str' object has no attribute 'descendants'

pandas - 对 pandas 数据框进行签名检查