Spark 计算文本文件数据平均值 - Python 实现
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
lines = spark.read.text('data01.txt').rdd
score = lines.map(lambda x: int(x[2]))
num = score.count()
total_score = score.reduce(lambda x, y: x + y)
avg = total_score / num
print(avg)
该代码使用 SparkSession 读取名为 'data01.txt' 的文本文件,然后使用 map 函数将每行数据的第三个字符转换为整数,并将其存储在 score RDD 中。接着使用 count 和 reduce 函数分别计算数据数量和总和,最后计算平均值并打印。
注意: 确保 data01.txt 文件存在且每行数据的第三个字符是可转换为整数的数字。
原文地址: https://www.cveoy.top/t/topic/kIz 著作权归作者所有。请勿转载和采集!