给定一个已排序的pandas.Series(或只是一个列表)对象,我想创建组(例如,列表或pandas.Series),以便组中相邻元素之间的差异小于某个阈值,例如:THRESHOLD = 2sorted_list = [1, 2, 10, 15, 16, 17, 20, 21]# ...result = [[1, 2], [10], [15, 16, 17], [20, 21]]
2 回答

qq_笑_17
TA贡献1818条经验 获得超7个赞
您可以使用diff和cumsum来标记组,然后使用groupby:
s = pd.Series(sorted_list)
s.groupby(s.diff().gt(THRESHOLD).cumsum()).apply(list).tolist()
# [[1, 2], [10], [15, 16, 17], [20, 21]]

catspeake
TA贡献1111条经验 获得超0个赞
使用
s = pd.Series(sorted_list)
[y.tolist() for x , y in s.groupby(s.diff().gt(THRESHOLD).cumsum())]
Out[167]: [[1, 2], [10], [15, 16, 17], [20, 21]]
添加回答
举报
0/150
提交
取消