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

如何基于≤10秒时间阈值对Pandas DataFrame去重

Pandas按用户+URL分组并过滤10秒内重复记录的简洁实现

问题描述

现有如下Pandas DataFrame,需按user、url列分组,移除同组内timestamp与上一条记录相差≤10秒的重复行:

timestamp                   user    url
0   2018-02-07 00:00:00+02:00   ip0     google.com # 首次出现
1   2018-02-07 00:00:02+02:00   ip1     xe.com # 首次出现
2   2018-02-07 00:00:10+02:00   ip7     facebook.com
3   2018-02-07 00:00:11+02:00   ip1     xe.com # 重复(≤10秒):删除
4   2018-02-07 00:00:13+02:00   ip1     xe.com # 不重复:保留
5   2018-02-07 00:00:15+02:00   ip2     example.com
6   2018-02-07 00:00:20+02:00   ip3     ebay.com
7   2018-02-07 00:00:55+02:00   ip1     xe.com # 不重复:保留
8   2018-02-07 00:00:59+02:00   ip5     amazon.com
9   2018-02-07 00:01:02+02:00   ip1     xe.com # 重复(≤10秒):删除
10  2018-02-07 00:01:28+02:00   ip0     google.com # 不重复:保留

尝试使用df = df.drop_duplicates(subset=['user', 'url'], keep='first'),但该方法会移除所有同user、url的行,无法识别时间阈值。期望得到如下结果:

timestamp                   user    url
0   2018-02-07 00:00:00+02:00   ip0     google.com
1   2018-02-07 00:00:02+02:00   ip1     xe.com
2   2018-02-07 00:00:10+02:00   ip7     facebook.com
4   2018-02-07 00:00:13+02:00   ip1     xe.com
5   2018-02-07 00:00:15+02:00   ip2     example.com
6   2018-02-07 00:00:20+02:00   ip3     ebay.com
7   2018-02-07 00:00:55+02:00   ip1     xe.com
8   2018-02-07 00:00:59+02:00   ip5     amazon.com
10  2018-02-07 00:01:28+02:00   ip0     google.com

需要最简洁的实现方式,比如通过生成掩码排除符合时间阈值的重复行。

解决方案

可以通过分组计算时间差+掩码过滤的方式实现,步骤如下:

  1. 确保timestamp列是时间类型(若未转换):
import pandas as pd

df['timestamp'] = pd.to_datetime(df['timestamp'])
  1. 生成过滤掩码并筛选数据:
# 计算每组内当前行与上一行的时间差
time_diff = df.groupby(['user', 'url'])['timestamp'].diff()
# 保留组内首行,或时间差超过10秒的行
mask = time_diff.isna() | (time_diff > pd.Timedelta(seconds=10))
# 得到结果数据集
result_df = df[mask]

原理说明

  • groupby(['user', 'url'])['timestamp'].diff():在每个user-url分组内,计算当前行与前一行的时间间隔,组内第一行因无前置数据,结果为NaT(无效时间)。
  • 掩码mask筛选两类有效行:分组的第一条记录,以及与上一条记录时间差大于10秒的记录。
  • 直接用掩码过滤原DataFrame,即可快速得到符合要求的结果,逻辑简洁且执行高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:50:24