首页 > 解决方案 > 将聊天数据划分为会话

问题描述

我在 csv 中有过去一年与客户聊天的数据。这一切都是按照他们的时间戳顺序排列的。我想为每个客户划分会话,以便我可以分析单独的聊天会话。

Timestamp            Customer        Message
2019-06-22 04:37:32     x        Hello, I price for 10 pens?
2019-06-22 04:38:11     y        whats the price of a new book?
2019-06-22 04:38:23     x        can you place an order for 9 only
2019-06-22 05:12:10     y        Ok I want to order 1
2019-06-22 05:17:45     z        Hello 
2019-06-22 06:31:12     x        Please cancel my order
2019-06-23 12:13:02     y        I want to place an order for 100 pencils 

我想以一种我可以根据某个时间范围然后由客户对它们进行分组的方式对这些数据进行分段。如果还有更好的方法,将其划分为聊天会话,我会非常高兴。谢谢。

标签: pythonpandas

解决方案


一个起点是在一个时间段(比如 60 分钟)内对您的数据集进行分组,count每个客户的时间范围内有多少条消息,以及每个客户list()的所有消息:

import pandas as pd
from datetime import datetime

# Convert to timestamp if needed
df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')  

# Perform the operation
res = df.groupby([pd.Grouper(key='Timestamp', freq='60min'),'Customer']).agg({'Message': lambda m: m.tolist(),'Customer':'count'})

# Rename the columns
res.rename(columns = {'Customer':'cust_msgs_per_hour'},inplace=True)

以上将为您提供:

res.sort_values('Customer')
Out[264]: 
                                                                        Message  cust_msgs_per_hour
Timestamp           Customer                                                                       
2019-06-22 04:00:00 x         [Hello, I price for 10 pens?, can you place an...                   2
2019-06-22 06:00:00 x                                  [Please cancel my order]                   1
2019-06-22 04:00:00 y                         [whats the price of a new book?]                   1
2019-06-22 05:00:00 y                                    [Ok I want to order 1]                   1
2019-06-23 12:00:00 y                [I want to place an order for 100 pencils]                   1
2019-06-22 05:00:00 z                                                   [Hello]                   1

推荐阅读