6.RDD综合练习:更丰富的操作
集合运算练习
union(), intersection(),subtract(), cartesian()

内连接与外连接
join(), leftOuterJoin(), rightOuterJoin(), fullOuterJoin()
多个考勤文件,签到日期汇总,出勤次数统计

三、综合练习:学生课程分数
网盘下载sc.txt文件,通过RDD操作实现以下数据分析:
>>> scm=sc.textFile("file:///home/hadoop/hw/sc.txt").map(lambda line:line.split(',')).map(lambda line:[line[0],line[1],int(line[2])])

持久化 scm.cache()

总共有多少学生?map(), distinct(), count()

开设了多少门课程?

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

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

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

有多少个100分?

Tom选修了几门课?每门课多少分?filter(), map() RDD

Tom选修了几门课?每门课多少分?map(),lookup() list

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

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



生成(课程,分数)RDD,观察keys(),values()

每个分数+5分。
mapValues(func)

map(func)

查看不及格人数的变化

求每门课的选修人数及所有人的总分。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()

求每门课的选修人数及平均分,精确到2位小数。map(),round()
>>> courseC.map(lambda x:(x[0],x[1][1],round(x[1][0]/x[1][1], 2))).collect()

求每门课的选修人数及平均分。用reduceByKey()实现,并比较与combineByKey()的异同。
>>> 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 a:(a[0],a[1][1],round(a[1][0]/a[1][1], 2))).collect() >>> reuslt

结果可视化。 pyecharts.charts,Bar()
前提:下载pyecharts库

>>> course_name = [i[0] for i in result]
>>> course_pnum = [i[1] for i in result]
>>> course_mean = [i[2] for i in result]
>>> from pyecharts.charts import Bar
>>> from pyecharts import options as opts
>>> bar = (
Bar(init_opts=opts.InitOpts(width="1500px"))
.add_xaxis(course_name)
.add_yaxis("选修人数", course_pnum)
.add_yaxis("平均分", course_mean)
.set_global_opts(title_opts=opts.TitleOpts(title="课程详情"),
toolbox_opts=opts.ToolboxOpts(),xaxis_opts=opts.AxisOpts(
axislabel_opts={"interval":"0"}))
)
>>> bar.render('course.html')

生成的.html会保存在/home/hadoop/course.html



浙公网安备 33010602011771号