如何用Python计算DataFrame中同车牌序列号行的时间间隔?
解决方法:用Pandas找出匹配行对并计算时间间隔
咱们一步步来搞定这个需求,核心思路是先把时间列转成可计算的格式,再通过分组找到plateno和serialno都匹配的行,最后生成行对并计算时间差。下面是具体实现:
步骤1:准备数据并转换时间列
首先得把from/arrive列从字符串转成datetime类型,不然没法计算时间间隔:
import pandas as pd # 替换成你实际的DataFrame data = { 'id': [755, 762, 920, 976], 'location': ['A', 'A', 'C', 'B'], 'plateno': ['ade2384', 'ax395', 'ax395', 'ade2384'], 'serialno': ['TA144', 'TB543', 'TB543', 'TA144'], 'type': [11014, 11014, 11000, 11000], 'from/arrive': ['2018-01-02 10:13:00', '2018-01-02 10:43:00', '2018-01-03 09:06:00', '2018-01-03 11:39:00'] } df = pd.DataFrame(data) # 转换时间列为datetime类型 df['from/arrive'] = pd.to_datetime(df['from/arrive'])
步骤2:筛选有匹配行的分组
按plateno和serialno分组,只保留组内至少有2行的分组(毕竟只有这样才有可配对的行):
# 分组后筛选出符合条件的行 grouped = df.groupby(['plateno', 'serialno']).filter(lambda x: len(x) >= 2)
步骤3:生成行对并计算时间间隔
用itertools.combinations生成每个分组内的所有两两行对,然后计算时间差:
from itertools import combinations # 存储结果的列表 result_list = [] # 遍历每个符合条件的分组 for (plate, serial), group in grouped.groupby(['plateno', 'serialno']): # 生成组内所有行的两两组合 for row_a, row_b in combinations(group.itertuples(index=False), 2): # 计算时间间隔(取绝对值避免负数,也可以用max-min保证正向差) time_diff = abs(row_a._asdict()['from/arrive'] - row_b._asdict()['from/arrive']) # 整理结果数据 result_list.append({ 'plateno': plate, 'serialno': serial, 'id_pair': (row_a.id, row_b.id), 'time_interval': time_diff, 'location_pair': (row_a.location, row_b.location), 'type_pair': (row_a.type, row_b.type) }) # 转成DataFrame方便查看和后续处理 result_df = pd.DataFrame(result_list)
步骤4:查看结果
运行后result_df会包含所有匹配行对的信息,比如你的示例数据会输出:
plateno=ade2384, serialno=TA144对应的id755和976,时间间隔为1天1小时26分钟plateno=ax395, serialno=TB543对应的id762和920,时间间隔为22小时23分钟
如果你的数据有上千行,这个方法也能高效处理——Pandas的分组操作经过优化,只要分组内的行数不是极端多,combinations的性能完全够用。
内容的提问来源于stack exchange,提问作者Tyson
相关产品推荐
相关产品推荐

