【问题标题】:How to combine two rdd into on rdd in spark(Python)如何在spark(Python)中将两个rdd组合成on rdd
【发布时间】:2017-10-27 07:07:34
【问题描述】:

比如有两个rdd,比如“rdd1 = [[1,2],[3,4]], rdd2 = [[5,6],[7,8]]”。以及如何将两者结合成这种风格:[[1,2,5,6],[3,4,7,8]]。有没有什么功能可以解决这个问题?

【问题讨论】:

  • Spark Dataset API - join的可能重复
  • 看到这个例子,我认为 join 不起作用,因为我找不到加入的密钥

标签: apache-spark pyspark rdd


【解决方案1】:

您需要使用 rdd.zip() 将您的 rdds 基本组合在一起,并对生成的 rdd 执行 map 操作以获得您想要的输出:

rdd1 = sc.parallelize([[1,2],[3,4]])
rdd2 = sc.parallelize([[5,6],[7,8]])

#Zip the two rdd together
rdd_temp = rdd1.zip(rdd2)

#Perform Map operation to get your desired output by flattening each element
#Reference : https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
rdd_final = rdd_temp.map(lambda x: [item for sublist in x for item in sublist])

#rdd_final.collect()
#Output : [[1, 2, 5, 6], [3, 4, 7, 8]]

您还可以在 Databricks 笔记本 at this link 上查看结果。

【讨论】:

  • 感谢 Mohammed Kashif 的帮助!我应该多练习。
【解决方案2】:

使用 rdd join 实现此目的的另一种(更长)方法:

rdd1 = sc.parallelize([[1,2],[3,4]])
rdd2 = sc.parallelize([[5,6],[7,8]])

# create keys for join
rdd1=rdd1.zipWithIndex().map(lambda (val, key): (key,val))
rdd2=rdd2.zipWithIndex().map(lambda (val, key): (key,val))
# join and flatten output
rdd_joined=rdd1.join(rdd2).map(lambda (key, (val1, val2)): val1+val2)

rdd_joined.take(2)

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 2015-06-15
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多