数据库
首页 > 数据库> > 08 学生课程分数的Spark SQL分析

08 学生课程分数的Spark SQL分析

作者:互联网

读学生课程分数文件chapter4-data01.txt,创建DataFrame。

>>> url = "file:///usr/local/spark/mycode/rdd/chapter4-data01.txt"

>>> rdd = spark.sparkContext.textFile(url).map(lambda line:line.split(','))

>>> rdd.take(3)

[['Aaron', 'OperatingSystem', '100'], ['Aaron', 'Python', '50'], ['Aaron', 'ComputerNetwork', '30']]

>>> from pyspark.sql.types import IntegerType,StringType,StructField,StructType

>>> from pyspark.sql import Row

>>> fields = [StructField('name',StringType(),True),StructField('course',StringType(),True),StructField('score',IntegerType(),True)]

>>> schema = StructType(fields)

>>> data = rdd.map(lambda p:Row(p[0],p[1],int(p[2])))

>>> df_scs = spark.createDataFrame(data,schema)

>>> df_scs.printSchema()

>>> df_scs.show()

 

 

用DataFrame的操作或SQL语句完成以下数据分析要求,并和用RDD操作的实现进行对比:

>>> df_scs.select('name','course',df_scs.score+5).show()

 

 

>>> df_scs.select('name').distinct().count()

 

 

>>> df_scs.select('course').distinct().show()

 

 

>>> df_scs.groupBy('name').count().show()

 

 

>>> df_scs.groupBy('course').count().show()

 

 

 

 

 

 

>>> df_scs.filter(df_scs.score>95).groupBy('course').count().show()

 

 

>>> df_scs.filter(df_scs.name=='Tom').show()

 

 

 

>>> df_scs.filter(df_scs.name=='Tom').orderBy(df_scs.score).show()

 

>>> df_scs.filter(df_scs.name=='Tom').agg({"score":"mean"}).show()

 

>>> df_scs.groupBy('course').avg('score').show()

  >>> df_scs.groupBy('course').max('score').show()

  >>> df_scs.groupBy('course').min('score').show()

>>> from pyspark.sql.functions import *
>>> df_scs.select(countDistinct('name').alias('学生人数'),countDistinct('course').alias('课程数'),round(mean('score'),2).alias('所有课的平均分')).show()

>>> df_scs.filter(df_scs.score<60).groupBy('course').count().show()

 

 

 

 

from pyspark.sql.types import IntegerType, StringType, StructField, StructType

fields = [StructField(...), ...]

schema = StructType(fields)

 类型:http://spark.apache.org/docs/latest/sql-ref-datatypes.html 

from pyspark.sql import Row

data = rdd.map(lambda p: Row(...))

 

Spark SQL DataFrame 操作

df.show()

df.printSchema()

df.count()

df.head(3)

df.collect()

df[‘name’]

df.name

df.first().asDict()

df.describe().show()

df.distinct()

df.filter(df['age'] > 21).show()

df.groupBy("age").count().show()

df.select('name', df['age‘] + 1).show()

df_scs.groupBy("course").avg('score').show()

 df_scs.agg({"score": "mean"}).show()

df_scs.groupBy("course").agg({"score": "mean"}).show()

 函数:http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#module-pyspark.sql.functions 

 

 

标签:name,show,df,08,course,score,SQL,Spark,scs
来源: https://www.cnblogs.com/jienijieni/p/14786310.html