在给定阈值内合并范围(间隔)的有效方法

2024-05-29 12:06:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一种有效的方法来计算距离,并在给定的距离内组合它们。例如,给定的范围和距离d=10

1   2
4   7
12  15
32  36
38  41
...

第一次迭代是:(4-2)->;2->;2<;10->;确定->;(1,7)

1   7
12  15
32  36
38  41
...

(12-7)->;5->;5-<;10->;正常->;(1,15)

1   15
32  36
38  41
...

(32-15)->;17->;17-<;10->;KO

1   15
32  36
38  41
...

(38-36)—>;2—>;2—<;10—>;正常—>;(32,41)

所需的(结果)数据集:

1   15
32  41
...

如果这个算法不能有效地实现,它的开销(列表、元组、循环)可能会给主程序带来风险。你知道吗

提前谢谢!!你知道吗


Tags: 数据方法ltgt算法距离列表ko
1条回答
网友
1楼 · 发布于 2024-05-29 12:06:18

数据源:

In [27]: df
Out[27]:
   start  end
0      1    2
1      4    7
2     12   15
3     32   36
4     38   41

In [28]: threshold = 10

矢量化解决方案:

In [31]: (df.groupby(df['start'].sub(df['end'].shift()).ge(threshold).cumsum())
    ...:    .agg({'start':'first','end':'last'}))
    ...:
Out[31]:
   start  end
0      1   15
1     32   41

说明:

In [32]: df['start'].sub(df['end'].shift())
Out[32]:
0     NaN
1     2.0
2     5.0
3    17.0
4     2.0
dtype: float64

In [33]: df['start'].sub(df['end'].shift()).ge(threshold)
Out[33]:
0    False
1    False
2    False
3     True
4    False
dtype: bool

In [34]: df['start'].sub(df['end'].shift()).ge(threshold).cumsum()
Out[34]:
0    0
1    0
2    0
3    1
4    1
dtype: int32

相关问题 更多 >

    热门问题