如何高效查找含指定时间与Veh_ID的pandas DataFrame的Group_ID
问题描述
我有一个结构如下的pandas DataFrame:
Date_Time Time_slot Veh_ID Pwr Group_ID 0 2023-03-30 00:00:01 1 100 10 100_1 1 2023-03-30 00:00:01 2 100 12 100_1 2 2023-03-30 00:00:05 1 100 3 100_1 3 2023-03-30 00:00:05 2 100 13 100_1 4 2023-03-30 00:00:22 1 100 22 100_1 5 2023-03-30 00:00:22 2 100 13 100_1 6 2023-03-30 00:00:01 1 55 8 55_1 7 2023-03-30 00:00:01 2 55 2 55_1 8 2023-03-30 00:00:05 1 55 12 55_1 9 2023-03-30 00:00:05 2 55 11 55_1 10 2023-03-30 00:22:00 1 100 7 100_2 11 2023-03-30 00:22:00 2 100 6 100_2 12 2023-03-30 00:25:00 1 100 11 100_2 13 2023-03-30 00:25:00 2 100 14 100_2 14 2023-03-30 00:23:00 1 55 7 55_2 15 2023-03-30 00:23:00 2 55 9 55_2 16 2023-03-30 00:35:00 1 55 9 55_2 17 2023-03-30 00:35:00 2 55 13 55_2 18 2023-03-30 01:35:00 1 55 10 55_2 19 2023-03-30 01:35:00 2 55 9 55_2
需求说明
需要实现一个高效的函数findGroup(date_time, veh),根据用户指定的日期时间和Veh_ID,找到对应的Group_ID。这里的"包含"指:指定的日期时间处于该Veh_ID对应Group_ID的时间区间内(即落在分组的起始到结束时间范围内)。
函数定义与示例
函数签名:
def findGroup(date_time, veh): ... return grpid
示例调用:
findGroup(pd.to_datetime('2023-03-30 00:23:00'), 100)
预期返回:100_2
目前可通过循环遍历每个分组并检查时间区间,但效率较低,需要更高效的实现方式。
高效实现方案
步骤1:预处理数据,生成分组时间区间映射
先对原始DataFrame做一次预处理,按Veh_ID和Group_ID分组,计算每个分组的起始、结束时间,生成便于快速查询的映射结构:
import pandas as pd # 假设原始DataFrame名为df # 按车辆+分组聚合,得到每个分组的时间范围 group_time_ranges = df.groupby(['Veh_ID', 'Group_ID'])['Date_Time'].agg(['min', 'max']).reset_index() # 转换为字典:键是Veh_ID,值是该车辆的所有分组信息(含Group_ID、起止时间) veh_group_map = group_time_ranges.groupby('Veh_ID').apply( lambda x: x[['Group_ID', 'min', 'max']].to_dict('records') ).to_dict()
步骤2:实现高效查询函数
利用预处理好的映射,直接定位目标车辆的分组,再通过向量化操作快速判断时间区间:
def findGroup(date_time, veh): # 获取当前车辆的所有分组信息 groups = veh_group_map.get(veh, []) if not groups: return None # 无匹配车辆时返回None # 转换为临时DataFrame做向量化判断 temp_df = pd.DataFrame(groups) # 筛选包含目标时间的分组 mask = (temp_df['min'] <= date_time) & (date_time <= temp_df['max']) matched_groups = temp_df[mask]['Group_ID'].tolist() # 假设每个时间点对应唯一Group_ID,返回第一个匹配项(多匹配场景可按需调整) return matched_groups[0] if matched_groups else None
方案优势
- 预处理仅需一次:后续重复查询无需再遍历原始大DataFrame,大幅提升查询效率
- 向量化替代循环:用pandas向量化运算替代纯Python循环,速度提升数倍
- 字典快速定位:通过Veh_ID直接锁定对应分组列表,避免无关数据遍历
内容的提问来源于stack exchange,提问作者earnric
相关产品推荐
相关产品推荐

