将唯一键值分配给每个流水线RDD中的元素

问题描述 投票:0回答:1

我有一个管道RDD:

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

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

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

我该怎么做?

pyspark jupyter-notebook bigdata rdd
1个回答
0
投票

使用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)]

现在使用地图切换值和索引的位置

districts=districts.map(lambda (x,y):(y,x))
districts.take(5)
[(0, '004'), (1, '022'), (2, '008'), (3, '003'), (4, '001')]
© www.soinside.com 2019 - 2024. All rights reserved.