You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选DataFrame中def类型行15秒内出现的att类型行?

Pandas数据筛选:保留特定时间范围内的'att'记录

原始数据

eventtimetype
12022-07-15 18:08:05def
22022-07-15 18:08:06att
32022-07-15 18:09:00def
42022-07-15 18:09:12def
52022-07-15 18:13:26def
62022-07-15 18:13:36att
72022-07-15 18:19:05def
82022-07-15 18:21:43def
92022-07-15 18:26:06att
102022-07-15 18:27:26def

需求说明

仅保留type为'att'且发生在最近一条type为'def'的记录之后15秒内的行。

实现代码

import pandas as pd

# 构造原始数据
data = {
    'event': [1,2,3,4,5,6,7,8,9,10],
    'time': ['2022-07-15 18:08:05', '2022-07-15 18:08:06', '2022-07-15 18:09:00', '2022-07-15 18:09:12', '2022-07-15 18:13:26', '2022-07-15 18:13:36', '2022-07-15 18:19:05', '2022-07-15 18:21:43', '2022-07-15 18:26:06', '2022-07-15 18:27:26'],
    'type': ['def','att','def','def','def','att','def','def','att','def']
}
df = pd.DataFrame(data)

# 1. 将time列转换为datetime类型
df['time'] = pd.to_datetime(df['time'])

# 2. 填充每条记录最近的前一条def记录的时间
df['last_def_time'] = df.loc[df['type'] == 'def', 'time'].ffill()

# 3. 计算时间差并筛选符合条件的行
df['time_diff'] = (df['time'] - df['last_def_time']).dt.total_seconds()
result = df[(df['type'] == 'att') & (df['time_diff'] <= 15)].drop(columns=['last_def_time', 'time_diff'])

print(result)

筛选结果

eventtimetype
22022-07-15 18:08:06att
62022-07-15 18:13:36att

内容的提问来源于stack exchange,提问作者Delopera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:17:21