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

如何基于Timestamp筛选Pandas DataFrame中符合条件的记录

解决方案

步骤说明

  1. 确保timestamp列转换为可比较的datetime类型
  2. 提取每个id访问location A的时间戳(若有多个A记录,取最新的一次访问时间)
  3. 将该时间戳合并回原DataFrame,用于后续条件判断
  4. 筛选出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)

输出结果

idlocationtimestamp
1001B2022-01-01 18:00:00
2001B2022-01-01 18:15:00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:31:18