PySpark:如何拆分成对RDD中的字符串值并使用键进行映射

2024-04-28 06:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

给定

data = sc.parallelize([(1,'winter is coming'),(2,'ours is the fury'),(3,'the old the true the brave')])

我期望的输出是

[('fury',[2],('true',[3]),('is',[1,2]),('old',[3]),('the',[2,3]),('ours',[2]),('brave',[3]),('winter',[1]),('coming',[1])]

我不确定如何映射以下输出

[(1,'winter'),(1,'is'),(1,'coming'),(2,'ours'),(2,'is'),....etc.]`

我试着用

data.flatMap(lambda x: [(x[0], v) for v in x[1]]

但这最终将键映射到字符串的每个字母,而不是单词此处是否应使用flatMap、map或split函数

映射之后,我计划使用

data.reduceByKey(lambda a,b: a+b).map(lambda x:(x[1],x[0])).collect()

我的想法正确吗


Tags: thelambdatruemapdataisoldfury
1条回答
网友
1楼 · 发布于 2024-04-28 06:11:31

您可以flatMap并创建元组,在元组中重用键并为每个单词创建条目(使用split()获得):

data.flatMap(lambda pair: [(pair[0], word) for word in pair[1].split()])

收集后,输出

[(1, 'winter'),
 (1, 'is'),
 (1, 'coming'),
 (2, 'ours'),
 (2, 'is'),
 (2, 'the'),
 (2, 'fury'),
 (3, 'the'),
 (3, 'old'),
 (3, 'the'),
 (3, 'true'),
 (3, 'the'),
 (3, 'brave')]

相关问题 更多 >