且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对列表中相同元素的索引进行分组的有效方法

更新时间:2023-02-05 13:14:52

使用熊猫GroupBy.apply,这非常简单-使用数据对一系列索引进行分组.一个不错的好处是,您可以保持索引的顺序.

Using pandas GroupBy.apply, this is pretty straightforward—use your data to group on a Series of indices. A nice bonus here is you get to keep the order of your indices.

data = [1, 2, 2, 5, 8, 3, 3, 9, 0, 1]
pd.Series(range(len(data))).groupby(data, sort=False).apply(list).tolist()
# [[0, 9], [1, 2], [3], [4], [5, 6], [7], [8]]