我想知道是否有一种计算范围距离的有效方法,并将它们组合在给定的距离上。例如,给定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
...这种算法的代价(列表、元组、循环)如果不能有效地实现,可能会给主程序带来风险。
提前谢谢你!!
发布于 2018-02-16 10:56:53
来源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: int32https://stackoverflow.com/questions/48825078
复制相似问题