python - 从另一个RDD的映射中的RDD查找

时间:2016-11-02 19:03:12

标签: python apache-spark

我有2个RDD:

  • RDD1 =(word,score)#word:string |得分:int
  • RDD2 =(id,text)#id:int |文字:单词列表

所以对于RDD2中的每个'id',我想计算文本中每个单词的得分平均值

def predecir(texto): 
    contador = 0    
    prediccion = 0
    for palabra in texto:
        puntaje = listaRDD.lookup(palabra)
        if puntaje:
                puntaje = puntaje[0]
                prediccion += puntaje
                contador += 1
    return (float(prediccion)/ contador)

listaTestRDD = listaTestRDD.map(lambda x: (x[0], predecir(x[1])))
print listaTestRDD.take(1)

我收到此错误消息

  

例外:您似乎正在尝试广播RDD或   引用动作或转换中的RDD。 RDD转换   并且操作只能由驱动程序调用,而不能在其他内部调用   变换;例如,rdd1.map(lambda x:rdd2.values.count()*   x)因为值转换和计数动作无效   无法在rdd1.map转换中执行。更多   信息,请参阅SPARK-5063。

我该怎么做才能解决?我不能在另一个内部使用两个RDD?如何将RDD1转换为字典以便在O(1)中找到一个单词?

1 个答案:

答案 0 :(得分:1)

尝试:

RDD2.flatMapValues(lambda x: x) \
    .map(lambda x: (x[1], x[0])) \
    .leftOuterJoin(RDD1) \
    .values() \
    .map(lambda x: (x[0], (x[1], 1) if x[1] is not None else (0, 0))) \
    .reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1])) \
    .mapValues(lambda x: x[0] / float(x[1]) if x[1] else 0.0)
相关问题