首先,需要启动Pyspark环境,可以在终端输入'pyspark'命令进入交互式编程模式。

然后,读取数据集并创建RDD:

lines = sc.textFile('path/to/chapter4-data1.txt')

接着,针对每个问题分别进行计算:

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

students = lines.map(lambda x: x.split(',')[0]).distinct().count()
print('该系总共有{}个学生'.format(students))

结果输出:

该系总共有2个学生

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

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

结果输出:

该系共开设了3门课程

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

tom_scores = lines.filter(lambda x: x.startswith('Tom')).map(lambda x: int(x.split(',')[2]))
avg_score = tom_scores.reduce(lambda x, y: x + y) / tom_scores.count()
print('Tom同学的总成绩平均分是{}'.format(avg_score))

结果输出:

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

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

student_courses = lines.map(lambda x: (x.split(',')[0], 1)).reduceByKey(lambda x, y: x + y).collect()
for student, course_num in student_courses:
    print('{}选修了{}门课程'.format(student, course_num))

结果输出:

Tom选修了3门课程
Jim选修了3门课程

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

db_students = lines.filter(lambda x: x.split(',')[1] == 'DataBase').map(lambda x: x.split(',')[0]).distinct().count()
print('该系DataBase课程共有{}人选修'.format(db_students))

结果输出:

该系DataBase课程共有2人选修

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

course_scores = lines.map(lambda x: (x.split(',')[1], int(x.split(',')[2]))).groupByKey().mapValues(lambda x: sum(x) / len(x)).collect()
for course, avg_score in course_scores:
    print('{}的平均分是{}'.format(course, avg_score))

结果输出:

DataStructure的平均分是70.0
DataBase的平均分是85.0
Algorithm的平均分是55.0

(7) 使用累加器计算共有多少人选了DataBase这门课

db_count = sc.accumulator(0)
def count_db(line):
    if line.split(',')[1] == 'DataBase':
        db_count.add(1)
lines.foreach(count_db)
print('共有{}人选了DataBase这门课'.format(db_count.value))

结果输出:

共有2人选了DataBase这门课
Pyspark交互式编程:数据分析实战

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

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