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

按10分钟增量拆分时间戳行代码失效,请求技术支持

解决时间戳超10分钟行的拆分问题

你的代码核心问题是保留了原始的超时长行——你只是新增了拆分后的子行,但原来那19行时间差超10分钟的数据依然存在,所以执行后这类数据的数量没有变化。正确的逻辑应该是:对超时长的行进行拆分替换,而非新增;符合时长要求的行直接保留。

修改后的实现代码

import pandas as pd
import numpy as np

def split_long_time_rows(df, start_col, end_col, time_limit_min=10):
    time_limit = pd.Timedelta(minutes=time_limit_min)
    split_rows = []
    
    for _, row in df.iterrows():
        start = row[start_col]
        end = row[end_col]
        total_diff = end - start
        
        # 时间差符合要求,直接保留原行
        if total_diff <= time_limit:
            split_rows.append(row.to_dict())
            continue
        
        # 拆分超时长的行
        current_start = start
        while current_start < end:
            current_end = min(current_start + time_limit, end)
            # 复制原行所有字段,替换起止时间
            new_row = row.to_dict()
            new_row[start_col] = current_start
            new_row[end_col] = current_end
            # 按子时间段占比分配Bus数量(保持总数与原行一致)
            segment_diff = current_end - current_start
            if pd.notna(row['Bus']):
                new_row['Bus'] = round(row['Bus'] * (segment_diff / total_diff), 0)
            # 重新计算Time_diff
            new_row['Time_diff'] = segment_diff
            
            split_rows.append(new_row)
            current_start = current_end
    
    # 转换为DataFrame并排序重置索引
    return pd.DataFrame(split_rows).sort_values(by=start_col).reset_index(drop=True)

关键改进点

  • 替换而非新增:超时长的行不再保留,而是拆分为多个符合要求的子行,彻底消除时间差超10分钟的数据
  • Bus列合理分配:按子时间段的时长占原时间段的比例计算Bus数量,确保拆分后总数与原行一致;如果Bus是均匀分布的计数,也可改为均分逻辑(比如row['Bus'] // num_segments,最后一段补余数)
  • 自动更新Time_diff:每个子行的Time_diff会重新计算,准确反映当前子时间段的长度

使用示例

假设原数据有一行:

Start_timeEnd_timeTime_diffBus
2024-01-01 00:00:002024-01-01 00:25:0025 min25

执行函数后会拆分为3行:

Start_timeEnd_timeTime_diffBus
2024-01-01 00:00:002024-01-01 00:10:0010 min10
2024-01-01 00:10:002024-01-01 00:20:0010 min10
2024-01-01 00:20:002024-01-01 00:25:005 min5

所有行的时间差都≤10分钟,且Bus总数保持25不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:14:52