RDD算子的操作实验
实验目的掌握RDD算子的基本用法
实验资源- student.txt
- VMware Workstation
- Ubuntu 16.04
- Jupyter Notebook
- Pyspark
student.txt中的数据一共分为6列,每一列含义如下表所示:
| 班级号 | 姓名 | 年龄 | 性别 | 课程 | 分数 |
|---|---|---|---|---|---|
练习题目:
(1) 读入studnet.txt文档,生成RDD
(2) 获得年龄大于20的学生
(3) 获得性别为男的学生
(4) 获得班级号为10的学生
(5) 获得语文课的平均分
(6) 获得每个学生的平均成绩
(7) 获得每个科目的最高分
实验步骤1、读入student.txt文档,生成RDD
rdd = sc.textFile("/home/test/student.txt")
rdd2 = rdd.map(lambda x : x.split(" "))
2、获得年龄大于20的学生
rdd2.filter(lambda x : int(x[2])>20).collect()
3、获得性别为男的学生
rdd2.filter(lambda x : x[3]=='男').collect()
4、获得班级号为10的学生
rdd2.filter(lambda x : int(x[0]) == 10).collect()
5、获得语文课的平均分
rdd3 = rdd2.filter(lambda x : x[4]=='chinese') sum = rdd3.map(lambda x : x[5]).reduce(lambda x,y:int(x)+int(y)) count = rdd3.count() avg = sum/count #64.16666666666667
6、获得每个学生的平均成绩
rdd4 = rdd2.map(lambda x:(x[1],int(x[5]))) rdd4.reduceByKey(lambda x,y:x+y).map(lambda x: (x[0],x[1]/3)).collect()
7、 获得每个科目的最高分
rdd5 = rdd2.map(lambda x : (x[4],int(x[5]))) rdd6 = rdd5.groupByKey() rdd6.map(lambda x : (x[0],max((x[1])))).collect()



