如何筛选DataFrame中def类型行15秒内出现的att类型行?
Pandas数据筛选:保留特定时间范围内的'att'记录
原始数据
| event | time | type |
|---|---|---|
| 1 | 2022-07-15 18:08:05 | def |
| 2 | 2022-07-15 18:08:06 | att |
| 3 | 2022-07-15 18:09:00 | def |
| 4 | 2022-07-15 18:09:12 | def |
| 5 | 2022-07-15 18:13:26 | def |
| 6 | 2022-07-15 18:13:36 | att |
| 7 | 2022-07-15 18:19:05 | def |
| 8 | 2022-07-15 18:21:43 | def |
| 9 | 2022-07-15 18:26:06 | att |
| 10 | 2022-07-15 18:27:26 | def |
需求说明
仅保留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)
筛选结果
| event | time | type |
|---|---|---|
| 2 | 2022-07-15 18:08:06 | att |
| 6 | 2022-07-15 18:13:36 | att |
内容的提问来源于stack exchange,提问作者Delopera
相关产品推荐
相关产品推荐

