在 pyspark 中对 RDD 的元素求和和除法

Sum and divide elements of a RDD in pyspark

我正在尝试对 RDD 的所有元素求和,然后除以元素数。我能够解决它,但使用不同的线路。但是我想只用一行使用 RDD 操作来完成。

RDD例如:

rdd_example = [(eliana,1),(peter,2),(andrew,3),(paul,4),(jhon,5)]

第一步是使用带有 lambda 的映射方法仅提取数字:

numbers = rdd_example.map(lambda x: x[1])

输出为:

numbers = [1,2,3,4,5]

然后对所有元素求和,使用方法reduce:

from operator import add
sum = numbers.reduce(add)

然后使用计数方法创建另一个变量来计算元素:

number_elem = rdd_example.count()

然后进行除法得到结果:

result = sum/number_elem 

我想只用一行,用一个变量来完成所有这些。

使用 fold,您可以一次性汇总计数和总和:

cnt, total = rdd_example.fold((0, 0), lambda res, x: (res[0] + 1, res[1] + x[1]))

print(total / cnt)
# 2.5

调用中注意,我们使用元组来存储计数和总和:

rdd_example.fold((0, 0), lambda res, x: (res[0] + 1, res[1] + x[1]))
#                 ^  ^                   ^^^^^^^^^^  ^^^^^^^^^^^^^^
#                 ^  init sum        add 1 to count / add value to sum
#                 init count

对于单线解决方案,注意您计算的是数字的平均值。 PySpark 已有 mean() 方法:

rdd_example = sc.parallelize([("eliana",1),("peter",2),("andrew",3),("paul",4),("jhon",5)])
result = rdd_example.map(lambda x: x[1]).mean()
print(result)
# output: 3.0