python - 在 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 中的说明对它进行分组。
解决方案
一个简单的解决方案是将列表转换为元组,然后如果您想知道每个组的索引,只需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]]
推荐阅读
- javascript - jquery获取在html中选择的整个选项
- c# - 列名未填充在 asp.net.cs 页面上
- php - show(Model $model) 在 Laravel 7 中不起作用
- c# - 从 Docker 运行的自动扩展 Kafka Consumer
- javascript - 我如何描述这两种价值传递方式之间的区别?
- java - 仅使用 Springboot 和 MongoDB 比较 YYYY-MM 部分日期
- pine-script - Strategy.long 后第二次交叉,Pine 脚本
- c# - 在长时间运行的工作人员服务中创建 HttpClient 对象的建议方法是什么
- bots - 对不和谐机器人的编码感到困惑
- reactjs - 在不渲染父组件 React js 的情况下重新渲染子组件