为每个元素流水线化的 RDD 分配唯一的键值

Posted

技术标签:

【中文标题】为每个元素流水线化的 RDD 分配唯一的键值【英文标题】:Assign unique key values to each element pipelined RDD 【发布时间】:2020-01-02 01:49:08 【问题描述】:

我有一个流水线RDD:

districts.take(5)
['004', '022', '008', '003', '001']

我希望每个元素都有一个唯一的键,例如:

[(1,'004'), (2, '022'), etc....]

我该怎么做?

【问题讨论】:

rdd.zipWithIndex() 【参考方案1】:

使用 zipWithIndex() 将索引添加到 rdd。

districts=sc.parallelize(['004', '022', '008', '003', '001'])
districts=districts.zipWithIndex()
districts.take(5)

[('004', 0), ('022', 1), ('008', 2), ('003', 3), ('001', 4)]

现在使用map来切换value和index的位置

districts=districts.map(lambda (x,y):(y,x))
districts.take(5)
[(0, '004'), (1, '022'), (2, '008'), (3, '003'), (4, '001')]

【讨论】:

以上是关于为每个元素流水线化的 RDD 分配唯一的键值的主要内容,如果未能解决你的问题,请参考以下文章