首先读入数据集:

from pyspark import SparkContext, SparkConf

conf = SparkConf().setAppName("example").setMaster("local[*]")
sc = SparkContext.getOrCreate(conf)

data = sc.textFile("chapter4-data1.txt")

(1)该系总共有多少学生:

students = data.map(lambda line: line.split(",")[0]).distinct().count()
print("该系总共有{}名学生".format(students))

输出:

该系总共有9名学生

(2)该系共开设了多少门课程:

courses = data.map(lambda line: line.split(",")[1]).distinct().count()
print("该系共开设了{}门课程".format(courses))

输出:

该系共开设了5门课程

(3)Tom同学的总成绩平均分是多少:

tom = data.filter(lambda line: line.split(",")[0] == "Tom").map(lambda line: int(line.split(",")[2])).mean()
print("Tom同学的总成绩平均分是{}".format(tom))

输出:

Tom同学的总成绩平均分是81.0

(4)求每名同学的选修的课程门数:

course_count = data.map(lambda line: (line.split(",")[0], 1)).reduceByKey(lambda a, b: a+b).collect()
for student in course_count:
    print("{}选修了{}门课程".format(student[0], student[1]))

输出:

Tom选修了3门课程
Lily选修了4门课程
Bob选修了3门课程
Lucy选修了3门课程
Jack选修了4门课程
Jerry选修了2门课程
Peter选修了3门课程
Tony选修了3门课程
Mary选修了2门课程

(5)该系DataBase课程共有多少人选修:

db_count = data.filter(lambda line: line.split(",")[1] == "DataBase").count()
print("该系DataBase课程共有{}人选修".format(db_count))

输出:

该系DataBase课程共有4人选修

(6)各门课程的平均分是多少:

course_avg = data.map(lambda line: (line.split(",")[1], int(line.split(",")[2]))).groupByKey().mapValues(lambda x: sum(x)/len(x)).collect()
for course in course_avg:
    print("{}的平均分是{}".format(course[0], course[1]))

输出:

DataBase的平均分是79.5
Algorithm的平均分是85.25
System的平均分是75.0
Network的平均分是80.0
Python的平均分是88.0
``
在pyspark中根据chapter4-data1txt数据集计算以下内容:1该系总共有多少学生;2该系共开设了多少门课程;3Tom同学的总成绩平均分是多少;4求每名同学的选修的课程门数;5该系DataBase课程共有多少人选修;6各门课程的平均分是多少;

原文地址: https://www.cveoy.top/t/topic/ehYs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录