最全Python+大数据学习笔记(一)_inferschema=true(1)

.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)**

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值