优化比较数据帧的函数

2024-06-26 00:13:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个记录一台信息亭机器使用情况的转换日志,还有一组记录机器在线/离线时间的日志。事务日志包含一个日期时间字段,它让您知道事务(或会话)何时发生

    event_date  raw_data1   session_id  ws_id
0   2017-11-06 12:13:06 {'description': 'Home'} 0604e80d-1ae6-48d0-81bf-32ca1dc58e4c    machine2
1   2017-11-06 12:13:41 {'description': 'AreYouStillThere'} 0604e80d-1ae6-48d0-81bf-32ca1dc58e4c    machine2
2   2017-11-06 12:14:09 {'description': 'AttractiveAnimation'}  0604e80d-1ae6-48d0-81bf-32ca1dc58e4c    machine2
3   2017-11-07 10:06:15 {'description': 'Home'} e2e7565f-60b4-4e7b-a8f0-d0a9c384b283    machine13
4   2017-11-07 10:06:27 {'description': 'AuthenticationPanelAdmin'} e2e7565f-60b4-4e7b-a8f0-d0a9c384b283    machine13

此函数的目标是查看哪个会话ID与脱机日志同步

    dtrange start   end status  machine_id
0   DateTimeTZRange(datetime.datetime(2017, 11, 17...   2017-11-17 14:46:15 2017-11-17 15:01:15 2   12
1   DateTimeTZRange(datetime.datetime(2017, 11, 17...   2017-11-17 14:47:02 2017-11-17 15:02:02 2   22
2   DateTimeTZRange(datetime.datetime(2017, 11, 17...   2017-11-17 14:47:23 2017-11-17 15:02:23 2   18
3   DateTimeTZRange(datetime.datetime(2017, 11, 17...   2017-11-17 14:48:09 2017-11-17 15:03:09 2   17
4   DateTimeTZRange(datetime.datetime(2017, 11, 17...   2017-11-17 14:49:18 2017-11-17 15:04:18 2   15

ws\u id和machine\u id是相同的,这使得它有点棘手,因为会话时间和machine\u id必须在两个数据帧之间匹配

这是我用来返回机器脱机时发生的所有会话ID的代码。它使用事务数据帧中的每一行过滤脱机数据帧,如果脱机事件与会话时间一致,则返回会话id:

def CheckSession(machinename, sessiontime, sessionid):
    if len(offlinedf[(offlinedf.start<sessiontime)
             &(offlinedf.end>sessiontime)
             &(offlinedf.name==machinename)])>0:
        return sessionid

sessions = df.apply(lambda row: CheckSession(row["name"], row["created_at1"], row["session_id"]), axis=1)

这会建立会话列表,但速度非常慢,而且数据帧非常大。我仍在学习如何最好地与熊猫图书馆合作-我希望使用一些矢量化优化它,但还没能想出如何以这种方式构建它


Tags: 数据机器iddatetime记录时间descriptionmachine
1条回答
网友
1楼 · 发布于 2024-06-26 00:13:10

考虑mergingdfofflinedfbyname,然后根据函数内部的逻辑使用^{}进行过滤。然后将过滤后的数据帧的sessionid列转换为一个列表

session_df = df.merge(offlinedf, on='name', suffixes=['', '_'])\
               .query('start < created_at1 & end > created_at1') 

sessions = session_df['sessionid'].tolist()

在任何数据分析工作中,对象的分块处理都比迭代行处理好

相关问题 更多 >