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

Pandas如何删除id相同且时间戳间隔不足6小时的冗余行

需求说明

需删除DataFrame中同时满足以下两个条件的行:

  • 存在其他行的or_enter_dt_tm时间戳与该行该字段值间隔在6小时以内
  • 两行的id字段值完全匹配
    注:同一组符合间隔要求的匹配行只需删除任意一条即可,无优先保留规则。
示例数据
import pandas as pd
import datetime

df_to_db = pd.DataFrame({
    'or_enter_dt_tm': ['2021-06-06 23:24:00', '2021-06-07 00:52:00', '2021-06-06 23:18:00',
                       '2021-06-01 07:59:00', '2021-07-20 19:24:00', '2021-07-24 15:00:00', '2021-07-20 14:24:00'],
    'or_exit_dt_tm': ['2021-06-06 23:54:00', '2021-06-07 01:58:00', '2021-06-06 23:58:00',
                      '2021-06-01 23:12:00', '2021-07-20 19:25:00', '2021-07-24 19:00:00', '2021-07-20 16:27:00'],
    'id': ['14', '14', '20', '20', '20', '35', '20']
})

# 转换为日期时间类型
df_to_db['or_enter_dt_tm'] = pd.to_datetime(df_to_db['or_enter_dt_tm'])
df_to_db['or_exit_dt_tm'] = pd.to_datetime(df_to_db['or_exit_dt_tm'])

原始DataFrame输出:

or_enter_dt_tm       or_exit_dt_tm  id
0 2021-06-06 23:24:00 2021-06-06 23:54:00  14
1 2021-06-07 00:52:00 2021-06-07 01:58:00  14
2 2021-06-06 23:18:00 2021-06-06 23:58:00  20
3 2021-06-01 07:59:00 2021-06-01 23:12:00  20
4 2021-07-20 19:24:00 2021-07-20 19:25:00  20
5 2021-07-24 15:00:00 2021-07-24 19:00:00  35
6 2021-07-20 14:24:00 2021-07-20 16:27:00  20
实现方案

本方案默认保留时间更早的记录,删除同id下时间靠后的、与前一条记录间隔不足6小时的行,若需保留时间更晚的记录,调整排序顺序即可。

# 按id和进入时间升序排序
df_sorted = df_to_db.sort_values(['id', 'or_enter_dt_tm'])
# 按id分组,计算相邻行的进入时间差,标记间隔小于6小时的行
drop_mask = df_sorted.groupby('id')['or_enter_dt_tm'].diff() < pd.Timedelta(hours=6)
# 获取待删除行的索引
drop_index = drop_mask[drop_mask].index
# 删除对应行
df_result = df_to_db.drop(drop_index)
输出结果
or_enter_dt_tm       or_exit_dt_tm  id
0 2021-06-06 23:24:00 2021-06-06 23:54:00  14
2 2021-06-06 23:18:00 2021-06-06 23:58:00  20
3 2021-06-01 07:59:00 2021-06-01 23:12:00  20
5 2021-07-24 15:00:00 2021-07-24 19:00:00  35
6 2021-07-20 14:24:00 2021-07-20 16:27:00  20

如果需要匹配示例中删除索引6的需求,将排序逻辑调整为按时间倒序即可:

df_sorted = df_to_db.sort_values(['id', 'or_enter_dt_tm'], ascending=[True, False])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:45:03