如何在PySpark groupByKey()中对迭代器中的值求和

2024-10-02 02:26:20 发布

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

我在Spark(Python)上做我的第一步,我在一个groupByKey()中与迭代器做斗争。我无法对值求和:我的代码如下所示:

example = sc.parallelize([('x',1), ('x',1), ('y', 1), ('z', 1)])

example.groupByKey()
x [1,1]
y [1]
z [1]

如何在Iterator上求和?我试过下面这样的方法,但没用

example.groupByKey().map(lambda (x,iterator) : (x,sum(iterator))
example.groupByKey().map(lambda (x,iterator) : (x,list(sum(iterator)))

Tags: 方法lambda代码mapexamplelistsparksum
3条回答

你也可以这样做:

wordCountsGrouped = wordsGrouped.groupByKey().map(lambda (x,y):(x,map(sum,y))).map(lambda (x,y):(x,y[0]))

有点晚了,但我刚找到解决办法

你可以简单地用summapValues

example.groupByKey().mapValues(sum)

尽管在这种特殊情况下reduceByKey更有效:

example.reduceByKey(lambda x, y: x + y)

或者

from operator import add

example.reduceByKey(add)

加上@zero323的答案,另一个解决方案是:

example.groupByKey().map(lambda (x,iterator) : (x,len(iterator)))

相关问题 更多 >

    热门问题