首页 > 解决方案 > 在 python 中将等价行分组为二维数组,用于非常大的数据集

问题描述

我有 100k 行,我想按照下面在 python 中的说明对它进行分组。一个简单的 python 迭代需要很多时间。如何使用任何 python ML 库对其进行优化?

    [[1,2,3,4],[2,3],[1,2,3],[2,3],[1,2,3],[1,2,3,4],[1],[2]...]

    Output
    [[0,5],[1,3]],[2,4],[6],[7]]

    Explanation:  index 0,5 have same list ;
                  index 1,3 have same list ;
                  index 2,4 have same list ; 
                  index 6 no match

我有 100k 子列表,我想按照上面在 python 中的说明对它进行分组。

标签: pythonpandasnumpymachine-learningdata-science

解决方案


一个简单的解决方案是将列表转换为元组,然后如果您想知道每个组的索引,只需groupby访问属性.groups

import pandas as pd
df = pd.DataFrame({'vals': [[1,2,3,4], [2,3], [1,2,3], [2,3],
                            [1,2,3], [1,2,3,4], [1], [2], [2,2], [2,1,3]]})

df.groupby(df.vals.apply(tuple)).groups
#{(1,): Int64Index([6], dtype='int64'),
# (1, 2, 3): Int64Index([2, 4], dtype='int64'),
# (1, 2, 3, 4): Int64Index([0, 5], dtype='int64'),
# (2,): Int64Index([7], dtype='int64'),
# (2, 1, 3): Int64Index([9], dtype='int64'),
# (2, 2): Int64Index([8], dtype='int64'),
# (2, 3): Int64Index([1, 3], dtype='int64')}

如果您需要该分组索引列表,请尝试以下操作:

df.reset_index().groupby(df.vals.apply(tuple))['index'].apply(list).sort_values().tolist()
#[[0, 5], [1, 3], [2, 4], [6], [7], [8], [9]]

推荐阅读