python - 对具有复杂关系的数据集进行重复数据删除
问题描述
对于以下问题,我正在寻找一种在大量数据上快速且有效的解决方案。我可以访问 databricks 基础设施,并且可以交替使用 SQL 和 Python (pyspark) 编写代码。问题如下——给定一个大约 1m 行的数据集,格式如下。
duplicate parent
2 1
3 1
4 1
5 2
3 2
2 6
2 7
3 7
8 9
10 12
11 8
15 14
13 15
14 10
我从火花表中获取这些数据。我现在试图得到两个结果:
1 - 找到每个家庭成员的根父母
member parent
1 []
2 [1,7]
3 [1,7]
4 [1]
5 [1,7]
6 [1,7]
7 []
8 [9]
9 []
10 [12]
11 [9]
12 []
13 [12]
14 [12]
15 [12]
2 - 将所有亲子关系汇集到“家庭”中
family
[1,2,3,4,5,6,7]
[8,9,11]
[10,12,13,14,15]
这是一个代表关系的 Python dict,我尝试解决结果 1 的工作但速度非常慢,可能是由于递归函数。我的问题是这种方法在处理大量数据时非常缓慢,我不确定我拥有的哪些工具最适合解决这个问题。熊猫?斯卡拉?纯Python?
test = {
'duplicate':[2,3,4,5,3,2,6,3,8,10,11,14,15,14],
'parent':[1,1,1,2,2,6,7,7,9,12,8,15,13,10]
}
result = {
'root_parent': [],
'duplicate': []
}
parents = test['parent']
duplicates = test['duplicate']
def find_parents(root_duplicate, duplicate, result):
parents_of_duplicate = [parents[i] for i, x in enumerate(duplicates) if x == duplicate]
if not parents_of_duplicate:
result['root_parent'].append(duplicate)
result['duplicate'].append(root_duplicate)
else:
for parent_of_duplicate in parents_of_duplicate:
find_parents(root_duplicate, parent_of_duplicate, result)
for duplicate in set(duplicates):
find_parents(duplicate, duplicate, result)
解决方案
我在这个 Stackoverflow 响应中找到了我的答案。似乎是一个常见的图形问题:
import networkx as nx
test = {
'duplicate':[2,3,4,5,3,2,6,3,8,10,11,14,15,14],
'parent':[1,1,1,2,2,6,7,7,9,12,8,15,13,10]
}
relations = zip(test['duplicate'], test['parent'])
G = nx.Graph()
G.add_edges_from(relations)
list(nx.connected_components(G))
出去:
[{1, 2, 3, 4, 5, 6, 7}, {8, 9, 11}, {10, 12, 13, 14, 15}]
推荐阅读
- php - 如何在有多个页面的网站上使用 Vue?
- r - Smooth.spline(lambda, pi0, df = smooth.df) 中的错误:在 qvalue 包中
- javascript - 如何为负值绘制不同的渐变填充?
- ios - SwiftUI 图像作为自定义“单选”按钮
- kdb - 如何将数字列表转换为 k 中的字符串?
- sql - 如何在一系列连续时间戳内对数据进行分组
- angular - 为什么 Angular 解析器在使用 of() 返回可观察对象时不返回任何数据,但在使用 of().pipe(delay(1000)) 时返回
- python - Sympy - 从三角方程得到两个解,我只期待一个
- .htaccess - 将 htaccess 文件转换为 nginx try_file 用于子文件夹
- javascript - 将数组 A 和 B 的差异添加到数组 A