猿问

如何对已排序的 pandas.Series 进行分组?

给定一个已排序的pandas.Series(或只是一个列表)对象,我想创建组(例如,列表或pandas.Series),以便组中相邻元素之间的差异小于某个阈值,例如:


THRESHOLD = 2

sorted_list = [1, 2, 10, 15, 16, 17, 20, 21]

# ...

result = [[1, 2], [10], [15, 16, 17], [20, 21]]


宝慕林4294392
浏览 194回答 2
2回答

qq_笑_17

您可以使用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

使用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]]
随时随地看视频慕课网APP

相关分类

Python
我要回答