Skip to main content
 首页 » 编程设计

python之在python中查找重叠的时间段

2025年01月19日10insus

我正在尝试检查同一 file_id 中的两个时间段(由它们的持续时间表示为 time_from 和 time_to)是否在以下数据帧中重叠:

df1 
    id,file_id,time_from,time_to 
    1,10,00:00:19,00:00:25 
    2,12,00:02:39,00:02:49 
    3,12,00:04:18,00:04:30 
    4,12,00:05:30,00:05:55 
    5,15,00:01:35,00:01:38 
    6,18,00:07:35,00:07:48 
 
 
df2  
    id,file_id,time_from,time_to 
    1,10,00:00:18,00:00:26 
    2,12,00:02:30,00:02:49 
    3,12,00:05:28,00:05:56 
    4,15,00:01:40,00:01:50 

基本上,我想计算同一 file_id 的两个数据帧中段重叠的次数,允许 time_from 和 time_to 之间给定的距离(比如 +/- 4 秒)。

输出应该是这样的:

file_id, number_of_overlapping_segments 
10, 1 
12, 2 
15, 1 
18, 0 

这是两个时间段不重叠且算法应返回 0 的唯一情况(假设距离 > 4 秒)。所有其他情况都应返回 1:

               [_____] 
 
   [________]           [______] 

到目前为止,我的方法是使用 pandas 将时间值左右(限制)延长 4 秒 给定的时间段并创建临时数据帧来保存具有重叠时间段的行。 示例:

import pandas as pd 
 
left_overlap = [] 
right_overlap = [] 
 
for f in list(set(df1.file_id) & set(df2.file_id)): 
    for t_from, t_from_lim in list(zip(df2[df2.file_id==f]['time_from'], 
                                       df1[df1file_id==f]['time_from_limit'])): 
        if t_from > t_from_lim: 
            left_overlap.append(df_2[(df2.file_id==audio) & \ 
                                             (df2.time_from==t_from)]) 
 
df_left_overlap = pd.concat(left_overlap).reset_index(drop=True) 
 
 
for f in list(set(df1.file_id) & set(df2.file_id)): 
    for t_to, t_to_lim in list(zip(df_left_overlap[df_left_overlap.file_id==f]['time_to'], 
                                       df1[df1.file_id==f]['time_to_limit'])): 
        if t_to < t_to_lim: 
            right_overlap.append( 
                df_left_overlap[(df_left_overlap.file_id==f) & \ 
                                    (df_left_overlap.time_to==t_to)]) 
 
overlap = pd.concat(right_overlap) 

我认为这个解决方案效率不高,我希望找到一种更可靠的方法。

提前致谢!

请您参考如下方法:

看起来您正在添加 time_from-(4 秒)和 time_to+(4 秒)的属性。 (那是 time_from_limit 和 time_to_limit 是什么?)看起来您也在尝试检测重叠,而实际上测试它们是否不重叠并否定它要容易得多。

例如(伪代码):

for segment1 in df1: 
    for segment2 in df2 records with matching fileid: 
        if not (segment1.['time_from'] >= segment2.['time_to'] + (4 seconds) or 
                segment2.['time_from'] >= segment1.['time_to'] + (4 seconds)): 
        # They overlap 
        counters[fileid]++