6.RDD综合练习:更丰富的操作

集合运算练习

union()intersection()subtract(), cartesian() 操作

内连接和外连接 : join(), leftOuterJoin(), rightOuterJoin(), fullOuterJoin()

出勤情况统计

三、综合练习:学生课程分数

1. 网盘下载sc.txt文件,并读取

>>> scm = sc.textFile("file:///root/tools/sc.txt").map(lambda line:line.split(',')).map(lambda line:[line[0],line[1],int(line[2])])

2.持久化scm

sc.cache()

3.统计总共有多少个学生,并且开设了多少门课程?

4.生成(姓名,课程分数)键值对RDD,观察keys(),values()

5.每个学生选修了多少门课?map(), countByKey()

6.每门课程有多少个学生选?map(), countByValue()

7.有多少个100分?

8.Tom选修了几门课?每门课多少分?lookup()和 filter()之间的比较

9.Tom的成绩按分数大小排序。filter(), map(), sortBy()

10.Tom的平均分。map(),lookup(),mean()

11.生成(姓名课程,分数)RDD,观察keys(),values()

12.每个分数+20平时分,并且查看不合格的人数的变化(分别使用mapValues和map实现)

使用mapValues实现

使用map实现

13.求每门课的选修人数并求每门课的平均分,结果精确到两位小数** (分别使用combineByKey和reduceByKey实现)**

使用combineByKey实现

>>> course = scm.map(lambda line:(line[1],line[2]))
>>> courseC = course.combineByKey(
...     lambda v:(int(v),1),
...     lambda c,v:(c[0]+int(v),c[1]+1),
...     lambda c1,c2:(c1[0]+c2[0],c1[1]+c2[1]))
>>> courseC.collect()

>>> courseC.map(lambda x:(x[0],x[1][1],round(x[1][0]/x[1][1], 2))).collect()

使用reduceByKey实现

>>> course = scm.map(lambda line:(line[1],(line[2],1)))
>>> result = course.reduceByKey(lambda x,y:(x[0]+y[0],x[1]+y[1])).map(lambda c:(c[0],c[1][1],round(c[1][0]/c[1][1]))).collect()
>>> result

posted @ 2022-04-13 15:28  牛蛙点点  阅读(93)  评论(0编辑  收藏  举报