from pyspark import SparkContext, SparkConf
import os
from pyspark.sql.session import SparkSession
from pyspark.sql import Row def CreateSparkContex():
sparkconf = SparkConf().setAppName("MYPRO").set("spark.ui.showConsoleProgress", "false")
sc = SparkContext(conf=sparkconf)
print("master:" + sc.master)
sc.setLogLevel("WARN")
Setpath(sc)
spark = SparkSession.builder.config(conf=sparkconf).getOrCreate()
return sc, spark def Setpath(sc):
global Path
if sc.master[:5] == "local":
Path = "file:/C:/spark/sparkworkspace"
else:
Path = "hdfs://test" if __name__ == "__main__":
print("Here we go!\n")
sc, spark = CreateSparkContex()
readcsvpath = os.path.join(Path, 'iris.csv')
dfcsv = spark.read.csv(readcsvpath, header=True,
schema=("`Sepal.Length` DOUBLE,`Sepal.Width` DOUBLE,`Petal.Length` DOUBLE,`Petal.Width` DOUBLE,`Species` string"))
#指定数据类型读取 dfcsv.show(3) dfcsv.registerTempTable('Iris')#创建并登陆临时表
spark.sql("select * from Iris limit 3").show()#使用sql语句查询
spark.sql("select Species,count(1) from Iris group by Species").show() df = dfcsv.alias('Iris1')#创建一个别名
df.select('Species', '`Sepal.Width`').show(4)#因表头有特殊字符需用反引号``转义
df.select(df.Species,df['`Sepal.Width`']).show(4)
dfcsv.select(df.Species).show(4)#原始名、别名的组合
df[df.Species, df['`Sepal.Width`']].show(4)
df[['Species']]#与pandas相同
df['Species']#注意这是一个字段名 #########增加字段
df[df['`Sepal.Length`'], df['`Sepal.Width`'], df['`Sepal.Length`'] - df['`Sepal.Width`']].show(4)
df[df['`Sepal.Length`'], df['`Sepal.Width`'],
(df['`Sepal.Length`'] - df['`Sepal.Width`']).alias('rua')].show(4)#重命名 #########筛选数据
df[df.Species == 'virginica'].show(4)#与pandas筛选一样
df[(df.Species == 'virginica') & (df['`Sepal.Width`']>1)].show(4)#多条件筛选
df.filter(df.Species == 'virginica').show(4)#也可以用fileter方法筛选
spark.sql("select * from Iris where Species='virginica'").show(4)#sql筛选 ##########多字段排序
spark.sql("select * from Iris order by `Sepal.Length` asc ").show(4)#升序
spark.sql("select * from Iris order by `Sepal.Length` desc ").show(4)#降序
spark.sql("select * from Iris order by `Sepal.Length` asc,`Sepal.Width` desc ").show(4)#升降序 df.select('`Sepal.Length`', '`Sepal.Width`').orderBy('`Sepal.Width`',ascending=0).show(4)#按降序
df.select('`Sepal.Length`', '`Sepal.Width`').orderBy('`Sepal.Width`').show(4) # 升序
df.select('`Sepal.Length`', '`Sepal.Width`').orderBy('`Sepal.Width`', ascending=1).show(4) # 按升序,默认的
df.select('`Sepal.Length`', '`Sepal.Width`').orderBy(df['`Sepal.Width`'].desc()).show(4) # 按降序 df.select('`Sepal.Length`', '`Sepal.Width`').orderBy(
['`Sepal.Length`','`Sepal.Width`'], ascending=[0,1]).show(4)#两个字段按先降序再升序
df.orderBy(df['`Sepal.Length`'].desc(),df['`Sepal.Width`']).show(4) ##########去重
spark.sql("select distinct Species from Iris").show()
spark.sql("select distinct Species,`Sepal.Width` from Iris").show() df.select('Species').distinct().show()
df.select('Species','`Sepal.Width`').distinct().show()
df.select('Species').drop_duplicates().show()#同上,与pandas用法相同
df.select('Species').dropDuplicates().show()#同上 ##########分组统计
spark.sql("select Species,count(1) from Iris group by Species").show()
df[['Species']].groupby('Species').count().show()
df.groupby(['Species']).agg({'`Sepal.Width`': 'sum'}).show()
df.groupby(['Species']).agg({'`Sepal.Width`': 'sum', '`Sepal.Length`': 'mean'}).show() #########联结数据
dic=[['virginica','A1'],['versicolor','A2'],['setosa','A3']]
rrd=sc.parallelize(dic)
df2=rrd.map(lambda p: Row(lei=p[0],al=p[1]))
df2frame=spark.createDataFrame(df2)
df2frame.show()
df2frame.registerTempTable('dictable')
spark.sql("select * from Iris u left join dictable z on u.Species=z.lei").show()
df.join(df2frame, df.Species == df2frame.lei, 'left_outer').show() sc.stop()
spark.stop()

 

pyspark SparkSession及dataframe基本操作的更多相关文章

  1. DataFrame基本操作

    这些操作在网上都可以百度得到,为了便于记忆自己再根据理解总结在一起.---------励志做一个优雅的网上搬运工 1.建立dataframe (1)Dict to Dataframe df = pd. ...

  2. 将 数据从数据库 直接通过 pyspark 读入到dataframe

    from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .appName("Python Spark S ...

  3. [Spark SQL] SparkSession、DataFrame 和 DataSet 练习

    本課主題 DataSet 实战 DataSet 实战 SparkSession 是 SparkSQL 的入口,然后可以基于 sparkSession 来获取或者是读取源数据来生存 DataFrameR ...

  4. python做数据分析pandas库介绍之DataFrame基本操作

    怎样删除list中空字符? 最简单的方法:new_list = [ x for x in li if x != '' ] 这一部分主要学习pandas中基于前面两种数据结构的基本操作. 设有DataF ...

  5. 用python做数据分析pandas库介绍之DataFrame基本操作

    怎样删除list中空字符? 最简单的方法:new_list = [ x for x in li if x != '' ] 这一部分主要学习pandas中基于前面两种数据结构的基本操作. 设有DataF ...

  6. pandas库介绍之DataFrame基本操作

    怎样删除list中空字符? 最简单的方法:new_list = [ x for x in li if x != '' ] 今天是5.1号. 这一部分主要学习pandas中基于前面两种数据结构的基本操作 ...

  7. 用python做数据分析4|pandas库介绍之DataFrame基本操作

    原文地址 怎样删除list中空字符? 最简单的方法:new_list = [ x for x in li if x != '' ] 今天是5.1号. 这一部分主要学习pandas中基于前面两种数据结构 ...

  8. 机器学习三剑客之Pandas中DataFrame基本操作

    Pandas 是基于Numpy 的一种工具,是为了解决数据分析任务而创建的.Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具.Pandas提供了大量能使我们快速便捷 ...

  9. sparksession创建DataFrame方式

    spark创建dataFrame方式有很多种,官方API也比较多 公司业务上的个别场景使用了下面两种方式 1.通过List创建dataFrame /** * Applies a schema to a ...

随机推荐

  1. MVC全局用户验证之HttpModule

    在请求进入到MVC的处理mcvHandler之前,请求先到达HttpModule,因此可以利用HttpModule做全局的用户验证. HttpModule MVC5之前的版本基于system.web. ...

  2. Usage of the @ (at) sign in ASP.NET

    from:http://www.mikesdotnetting.com/article/258/usage-of-the-at-sign-in-asp-net Thursday, January 22 ...

  3. PostgreSQL 速查、备忘手册 | PostgreSQL Quick Find and Tutorial

    PostgreSQL 速查.备忘手册 作者:汪嘉霖 这是一个你可能需要的一个备忘手册,此手册方便你快速查询到你需要的常见功能.有时也有一些曾经被使用过的高级功能.如无特殊说明,此手册仅适用于 Linu ...

  4. 使用Recyclerview实现图片水平自动循环滚动

    简介: 本篇博客主要介绍的是如何使用RecyclerView实现图片水平方向自动循环(跑马灯效果) 效果图: 思路: 1.准备m张图片 1.使用Recyclerview实现,返回无数个(实际Inter ...

  5. constexpr函数------c++ primer

    constexpr函数是指能用于常量表达式的函数.定义constexpr函数的方法有其他函数类似,不过要遵循几项约定:函数的返回值类型及所以形参的类型都是字面值类型,而且函数体中必须有且只有一条ret ...

  6. CString、string、string.h的区别

    CString.string.string.h的区别   CString:CString是MFC或者ATL中的实现,是MFC里面封装的一个关于字符串处理的功能很强大的类,只有支持MFC的工程才能使用. ...

  7. luoguP3302 [SDOI2013]森林

    https://www.luogu.org/problemnew/show/P3302 看到查询第 k 小,而且是一颗树,可以联想到在树上的主席树,a 和 b 路径中第 k 小可以通过在 a, b, ...

  8. ajax(Asynchronous JavaScript and XML) 异步js或者xml

    1.XMLHttpRequest 对象:向服务器发送局部的请求,异步获取执行 a.浏览器支持 b.语法: xmlhttp==new XMLHttpRequest(); xmlhttp.open(&qu ...

  9. 航天独角兽Spacex

    2018年2月7日下午3时45分,猎鹰重型火箭在位于卡纳维拉尔角的肯尼迪航天中心LC-39A平台顺利升空.火箭直升云霄,按照既定轨道持续升空,位于美国弗罗里达州卡纳维拉尔角的航天发射中心硝烟四起,非常 ...

  10. 修复win10无法双击打开txt文档.reg

    Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\.txt]@="txtfile""Content Type& ...