
本文介绍一种贪心算法策略,用于对含两个时间戳列的dataframe进行分组:每组内 timestamp1 和 timestamp2 的极差均不得超过4天,确保分组满足双重时间约束且尽可能容纳更多行。
本文介绍一种贪心算法策略,用于对含两个时间戳列的dataframe进行分组:每组内 timestamp1 和 timestamp2 的极差均不得超过4天,确保分组满足双重时间约束且尽可能容纳更多行。
在实际数据分析中,常需将时间序列记录按业务逻辑聚合成“时间窗口组”,但当存在两个独立时间维度(如事件发生时间 timestamp1 与处理完成时间 timestamp2)时,简单按单列排序分组会失效。本教程提供一种稳健、可复现的贪心分组方案:对 DataFrame 按任一时间列(推荐 timestamp1)升序排序后,逐行遍历,动态维护当前组的起始时间基准(start_timestamp1 和 start_timestamp2),仅当新行在任一时间维度上超出4天容忍阈值时才开启新组。
该策略的核心在于:
✅ 同时校验两个时间列的跨度约束;
✅ 以首次进入组的行作为该组的“锚点”(即 min(timestamp1) 和 min(timestamp2));
✅ 严格满足 (current - anchor).days ≤ 4 对两列均成立,否则新建组;
✅ 时间复杂度为 O(n),适用于中等规模数据(百万行以内)。
以下是完整实现代码(含注释与验证):
import pandas as pd
# 构造示例数据
data = {
'timestamp1': ['2022-02-18', '2022-02-19', '2022-02-21', '2022-03-11', '2022-03-12', '2022-03-30'],
'timestamp2': ['2023-01-02', '2023-01-04', '2023-01-11', '2024-02-05', '2024-02-06', '2024-02-07']
}
df = pd.DataFrame(data)
df['timestamp1'] = pd.to_datetime(df['timestamp1'])
df['timestamp2'] = pd.to_datetime(df['timestamp2'])
# 关键:必须先排序!否则分组逻辑无意义
df = df.sort_values(['timestamp1', 'timestamp2']).reset_index(drop=True)
def assign_dual_timestamp_groups(df, max_span_days=4):
"""
基于 timestamp1 和 timestamp2 双重约束的贪心分组函数
每组内:max(timestamp1) - min(timestamp1) max_span_days
t2_violated = (row['timestamp2'] - anchor_t2).days > max_span_days
if t1_violated or t2_violated:
current_group += 1
# 更新锚点为当前行(新组起点)
anchor_t1 = row['timestamp1']
anchor_t2 = row['timestamp2']
groups.append(current_group)
return pd.Series(groups, index=df.index)
# 应用分组
df['group'] = assign_dual_timestamp_groups(df)
print(df[['timestamp1', 'timestamp2', 'group']])
输出结果:
timestamp1 timestamp2 group 0 2022-02-18 2023-01-02 1 1 2022-02-19 2023-01-04 1 2 2022-02-21 2023-01-11 2 3 2022-03-11 2024-02-05 3 4 2022-03-12 2024-02-06 3 5 2022-03-30 2024-02-07 4
⚠️ 重要注意事项:
- 排序不可省略:必须按 timestamp1(或 timestamp2)升序排列,否则贪心逻辑无法保证局部最优 → 全局合理;若业务要求兼顾两列顺序,建议以更关键的时间列为主排序键。
- 非最优解说明:该算法是贪心策略,不保证全局最少分组数(NP-hard 类似装箱问题),但实践表明其分组密度高、逻辑透明、易于调试。
- 边界处理:.days 属性自动向下取整,若需包含起止日的“日历跨度”,可改用 (row - anchor).components.days 或自定义日期差函数。
- 扩展性提示:如需支持多列联合约束或滑动窗口语义,建议迁移到 pd.cut() + 自定义 bin 边界,或使用 sklearn.cluster.AgglomerativeClustering 进行距离聚类(需定义时间差为欧氏距离)。
通过本方法,你可快速构建符合双重时间窗口约束的分组标签,为后续聚合统计、生命周期分析或批量任务调度提供可靠基础。











