培训系列5--spark 的 RDD 的 reduce方法使用
1.spark-shell环境下准备数据
val collegesRdd= sc.textFile("/user/hdfs/CollegeNavigator.csv")
val header= collegesRdd.first
val headerlessRdd= collegesRdd.filter( line=>{ line!= header } )
2.准备学生数的map
val countStuMap= headerlessRdd.map(line=>{
val strCount=line.split("\",\"")(7)
if (strCount.length()>0) strCount.toInt
else 0
})
countStuMap.take(10).foreach(println)
在map函数里面增加if else语句主要是数据中“”的空字符串,如果直接转换int会报错
3.写r求学生总数的reduce rdd
val totalcount=countStuMap.reduce((stuCount1,stuCount2)=>stuCount1+stuCount2)
得到所有学校的学生综述
3.写求学校类型的总数
scala> header
res12: String = "Name","Address","Website","Type","Awards offered","Campus setting","Campus housing","Student population","Undergraduate students","Graduation Rate","Transfer-Out Rate","Cohort Year *","Net Price **","Largest Program","IPEDS ID","OPE ID"
scala> val typeMap= headerlessRdd.map(line=>{
| val strtype=line.split("\",\"")(3)
| strtype
| })
typeMap: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[13] at map at <console>:30
scala> typeMap.count
res13: Long = 503
scala> typeMap.distinct.count
res14: Long = 5
一个rdd中如果有重复的值,可以直接通过distinct来去重。
4.求平均学校学生人数
求学校总数,可以通过headerlessRdd.count来获得,也可以用map reduce来做,map和reduce可以连写,
val collegeCount=headerlessRdd.map(line=>1).reduce((line1,line2)=>line1+line2)
totalcount/collegeCount
这里的数据量比表少,如果数据量比较多,会发发现平均值不对。
主要是由于计算totalcount的时候使用了int类型,int类型的最大值是有限的,实际计算中要把toInt 最好换成 toLong
if (strCount.length()>0) strCount.toLong
else 0