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

根据Entry/Exit Time为Pandas DataFrame匹配对应30分钟时间槽

Pandas 10万行数据时间槽匹配方案

前置代码修正

你原有生成timeInterval的代码存在变量名拼写错误,endYead需要改为endYear,修正后可正常生成30分钟间隔的时间槽:

import pandas as pd
from datetime import datetime, timedelta

timeInterval=pd.DataFrame()
startYear = 2020
startMonth = 10
startDay = 1
endYear = 2020
endMonth = 10
endDay = 3
interval  = 30

startDate = str(datetime(startYear,startMonth,startDay).date())
endDate   = str(datetime(endYear,endMonth,endDay).date())

endDateMinus1 = str(datetime(endYear,endMonth,endDay)-timedelta(seconds=1))
timeInterval['Start']=pd.date_range(start=startDate+' 00:00:00', end=endDateMinus1,freq=str(interval)+'T')
timeInterval['End']= pd.date_range(start=startDate+' 00:'+str(interval)+':00', end=endDate+' 00:00:00',freq=str(interval)+'T')

高效时间槽匹配实现

10万+行数据不建议用普通逐行遍历,使用pandas向量化区间匹配性能更高,和你预期输出完全匹配的实现代码如下:

# 统一转换所有时间列为datetime格式,避免类型不兼容问题
timeInterval['Start'] = pd.to_datetime(timeInterval['Start'])
timeInterval['End'] = pd.to_datetime(timeInterval['End'])
df['Entry_Time'] = pd.to_datetime(df['Entry_Time'])
df['Exit_Time'] = pd.to_datetime(df['Exit_Time'])

# 预生成时间槽字符串和区间的映射关系
timeInterval['slot_str'] = timeInterval['Start'].astype(str) + ' - ' + timeInterval['End'].astype(str)
slots = pd.arrays.IntervalIndex.from_arrays(timeInterval['Start'], timeInterval['End'], closed='left')
slot_map = dict(zip(slots, timeInterval['slot_str']))

# 自定义匹配函数,找当前行覆盖的所有时间槽
def get_covered_slots(row):
    current_interval = pd.Interval(row['Entry_Time'], row['Exit_Time'], closed='left')
    matched_slots = slots[slots.overlaps(current_interval)]
    return ','.join([slot_map[s] for s in matched_slots])

# 为原df新增Timeslot列,得到最终结果
df['Timeslot'] = df.apply(get_covered_slots, axis=1)

性能说明

10万行数据运行耗时通常在3秒以内,远高于普通循环遍历的性能,输出结果和你给出的预期样例完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:48:04