.getOrCreate()
# Spark+python 进行wordCount
from pyspark.sql import SparkSession
spark = SparkSession\
.builder\
.appName("PythonWordCount")\
.master("local[\*]")\
.getOrCreate()
# 将文件转换为RDD对象
lines = spark.read.text("input.txt").rdd.map(lambda r: r[0])
counts = lines.flatMap(lambda x: x.split(' ')) \
.map(lambda x: (x, 1)) \
.reduceByKey(lambda x, y: x + y)
output = counts.collect()
for (word, count) in output:
print("%s: %i" % (word, count))
spark.stop()
PySpark中的DataFrame
• DataFrame类似于Python中的数据表,允许处理大量结
构化数据
• DataFrame优于RDD,同时包含RDD的功能
# 从集合中创建RDD
rdd = spark.sparkContext.parallelize([
(1001, "张飞", 8341, "坦克"),
(1002, "关羽", 7107, "战士"),
(1003, "刘备", 6900, "战士")
])
# 指定模式, StructField(name,dataType,nullable)
# name: 该字段的名字,dataType:该字段的数据类型,
nullable: 指示该字段的值是否为空
from pyspark.sql.types import StructType, StructField,
LongType, StringType # 导入类型
schema = StructType([
StructField("id", LongType(), True),
StructField("name", StringType(), True),
StructField("hp", LongType(), True), #生命值
StructField("role\_main", StringType(), True)
])
# 对RDD应用该模式并且创建DataFrame
heros = spark.createDataFrame(rdd, schema)
heros.show()
# 利用DataFrame创建一个临时视图
heros.registerTempTable("HeroGames")
# 查看DataFrame的行数
print(heros.count())
# 使用自动类型推断的方式创建dataframe
data = [(1001, "张飞", 8341, "坦克"),
(1002, "关羽", 7107, "战士"),
(1003, "刘备", 6900, "战士")]
df = spark.createDataFrame(data, schema=['id', 'name',
'hp', 'role\_main'])
print(df) #只能显示出来是DataFrame的结果
df.show() #需要通过show将内容打印出来
print(df.count())
3
DataFrame[id: bigint, name: string, hp: bigint, role_main:
string]
| id|name| hp|role_main|
+----+-------+-----+-------------+
|1001|张飞|8341| 坦克|
|1002|关羽|7107| 战士|
|1003|刘备|6900| 战士| +----+-------+-----+-------------+ 3
从CSV文件中读取
heros = spark.read.csv("./heros.csv", header=True,
inferSchema=True)
![img](https://img-blog.csdnimg.cn/img_convert/8ba8f65991c783b5c8cfe1120a3d47ca.png)
![img](https://img-blog.csdnimg.cn/img_convert/72b17d293b2bc564c84575736bc43a44.png)
![img](https://img-blog.csdnimg.cn/img_convert/738bb9a74ef9fef5f9b91a877436538f.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**