根据pyspark中值的相似性减少键、值对

anauzrmj  于 2021-07-13  发布在  Spark
关注(0)|答案(1)|浏览(283)

我是Pypark的初学者。
我想找出值中具有相同数字的字母对,然后找出哪对字母出现的频率更高。
这是我的数据

data = sc.parallelize([('a', 1), ('b', 4), ('c', 10), ('d', 4), ('e', 4), ('f', 1), ('b', 5), ('d', 5)])
data.collect()
[('a', 1), ('b', 4), ('c', 10), ('d', 4), ('e', 4), ('f', 1), ('b', 5), ('d', 5)]

我想要的结果如下:

1: a,f
4: b, d
4: b, e
4: d, e
10: c
5: b, d

我尝试了以下方法:

data1= data.map(lambda y: (y[1], y[0]))
data1.collect()
[(1, 'a'), (4, 'b'), (10, 'c'), (4, 'd'), (4, 'e'), (1, 'f'), ('b', 5), ('d', 5)]

data1.groupByKey().mapValues(list).collect()
[(10, ['c']), (4, ['b', 'd', 'e']), (1, ['a', 'f']), (5, ['b', 'd'])]

正如我所说的,我对pyspark非常陌生,并试图搜索命令,但没有成功。谁能帮我一下吗?

dwbf0jvd

dwbf0jvd1#

你可以用 flatMap 用python itertools.combinations 从分组值中获取2的组合。另外,更喜欢使用 reduceByKey 而不是 groupByKey :

from itertools import combinations

result = data.map(lambda x: (x[1], [x[0]])) \
    .reduceByKey(lambda a, b: a + b) \
    .flatMap(lambda x: [(x[0], p) for p in combinations(x[1], 2 if (len(x[1]) > 1) else 1)])

result.collect()

# [(1, ('a', 'f')), (10, ('c',)), (4, ('b', 'd')), (4, ('b', 'e')), (4, ('d', 'e')), (5, ('b', 'd'))]

如果要在tuple只有一个元素时获取none,可以使用以下方法:

.flatMap(lambda x: [(x[0], p) for p in combinations(x[1] if len(x[1]) > 1 else x[1] + [None], 2)])

相关问题