首页 > 解决方案 > 在 PySpark 配对的 RDD 中搜索值,以获取来自另一个 RDD 的键

问题描述

我是 PySpark 的新手,我想做以下事情,

考虑以下代码,

import numpy as np
b =np.array([[1,2,100],[3,4,200],[5,6, 300],[7,8, 400]])
a = np.array([[1,2],[3,4],[11,6],[7,8], [1, 2], [7,8]])
RDDa = sc.parallelize(a)
RDDb = sc.parallelize(b)
dsmRDD = RDDb.map(lambda x: (list(x[:2]), x[2]))

我想获取与 RDDa 的每个值关联的值作为 dsmRDD 的键,即

result = [100, 200, 0, 400, 100, 400] 

非常感谢你。

标签: pysparkkey-value

解决方案


正如另一个答案所暗示的那样,您可以转换为数据框和join. 如果您只愿意继续rdd,您可以这样做,

import numpy as np

a = np.array([[1,2],[3,4],[11,6],[7,8], [1, 2], [7,8]])
b = np.array([[1,2,100],[3,4,200],[5,6, 300],[7,8, 400]])

RDDa = sc.parallelize(a)
RDDb = sc.parallelize(b)

dsmRDD = RDDa.zipWithIndex()\
         .map(lambda x: (tuple(x[0].tolist()),(0,x[1])))\
         .leftOuterJoin(RDDb.map(lambda x: (tuple(x[:2].tolist()), x[2])))\
         .map(lambda x: (x[1][0][1], x[1][1]) if x[1][1] is not None else (x[1][0][1],x[1][0][0]))

output = map(lambda x:x[1], sorted(dsmRDD.collect()))
print output

这给了你输出,

[100, 200, 0, 400, 100, 400]                                                    

推荐阅读