如何基于Timestamp筛选Pandas DataFrame中符合条件的记录
解决方案
步骤说明
- 确保
timestamp列转换为可比较的datetime类型 - 提取每个
id访问location A的时间戳(若有多个A记录,取最新的一次访问时间) - 将该时间戳合并回原DataFrame,用于后续条件判断
- 筛选出
location为B且timestamp晚于对应id的A访问时间的记录
代码实现
import pandas as pd # 构造初始DataFrame data = { 'id': ['001', '001', '001', '002', '003', '003'], 'location': ['A', 'B', 'B', 'B', 'B', 'A'], 'timestamp': ['2022-01-01 17:00:00', '2022-01-01 18:00:00', '2022-01-01 18:15:00', '2022-01-01 18:30:00', '2022-01-01 19:00:00', '2022-01-01 20:00:00'] } df = pd.DataFrame(data) # 转换时间列为datetime类型 df['timestamp'] = pd.to_datetime(df['timestamp']) # 获取每个id访问A的最新时间 id_a_timestamp = df[df['location'] == 'A'].groupby('id')['timestamp'].max() # 合并时间数据到原表 df = df.merge(id_a_timestamp.rename('a_time'), on='id', how='left') # 筛选目标记录 result = df[(df['location'] == 'B') & (df['timestamp'] > df['a_time'])].drop('a_time', axis=1) # 输出结果 print(result)
输出结果
| id | location | timestamp | |
|---|---|---|---|
| 1 | 001 | B | 2022-01-01 18:00:00 |
| 2 | 001 | B | 2022-01-01 18:15:00 |
内容的提问来源于stack exchange,提问作者crx91
相关产品推荐
相关产品推荐

