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

标签 python algorithm pandas merge biopython

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

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

第一次迭代将是:(4-2) -> 2 -> 2 < 10 -> OK -> (1,7)

1   7
12  15
32  36
38  41
...

(12-7) -> 5 -> 5 < 10 -> OK -> (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 -> OK -> (32,41)

所需(结果)数据集:

1   15
32  41
...

如果未有效实现,该算法(列表、元组、循环)的成本可能会给主程序带来风险。

提前致谢!

最佳答案

来源 DF:

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

关于python - 在给定阈值内合并范围(间隔)的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48825078/

相关文章:

python - pickle numpy 数组或列表时 pickle 文件大小

python - 瀑布图python?

python - 如何从 Python 中的文件名中删除前缀?

algorithm - 混合函数的增长顺序

python - pandas 合并彼此间隔不到 20 秒的交互

Python3 - 导入和重写方法

javascript - '固定' for 循环 - 什么更有效率?

algorithm - 使用 Map/Reduce 从多个 Sets 创建 Map

python - pandas 无法推断带双引号的 str 类型

python - Pandas 查询无值