pyspark学习rdd处理数据方法——学习记录

python黑马程序员

python 复制代码
"""
文件,按JSON字符串存储
1. 城市按销售额排名
2. 全部城市有哪些商品类别在售卖
3. 上海市有哪些商品类别在售卖
"""
from pyspark import SparkConf, SparkContext
import os
import json

os.environ['PYSPARK_PYTHON'] = r"D:\anaconda\envs\py10\python.exe"

# 创建SparkConf类对象
conf = SparkConf().setMaster("local[*]").setAppName("test_spark")
# 基于SparkConf类对象创建SparkContext对象
sc = SparkContext(conf=conf)

# 1. 城市按销售额排名
# 读取文件,获得rdd
file_rdd = sc.textFile("第15章资料\资料\orders.txt")
# 取出每个json字符串
json_str_rdd = file_rdd.flatMap(lambda x: x.split("|"))
# 将每个json字符串转换为字典
dict_rdd = json_str_rdd.map(lambda x: json.loads(x))
# 取出城市和销售额数据
# (城市,销售额)
city_with_money_rdd = dict_rdd.map(lambda x: (x['areaName'], int(x['money'])))
# 按城市分组,对销售额聚合
city_result_rdd = city_with_money_rdd.reduceByKey(lambda a, b: a+b)
# 销售额降序排列
result1 = city_result_rdd.sortBy(lambda x: x[1], ascending=False, numPartitions=1)
print("需求1的结果为:", result1.collect())

# 2. 全部城市有哪些商品类别在售卖
# 取出全部的商品类别
category_rdd = dict_rdd.map(lambda x: x['category']).distinct()
print("需求2的结果为:", category_rdd.collect())

# 3. 上海市有哪些商品类别在售卖
# 过滤出上海市的数据
beijing_data_rdd = dict_rdd.filter(lambda x: x['areaName'] == '上海')
result3 = beijing_data_rdd.map(lambda x:x['category']).distinct()
print("需求3的结果为:", result3.collect())


sc.stop()

结果:

相关推荐
Larry_Yanan8 小时前
Qt多进程(一)进程间通信概括
开发语言·c++·qt·学习
做cv的小昊9 小时前
【TJU】信息检索与分析课程笔记和练习(1)认识文献
经验分享·笔记·学习·搜索引擎·全文检索
再睡一夏就好10 小时前
深入Linux线程:从轻量级进程到双TCB架构
linux·运维·服务器·c++·学习·架构·线程
蒙奇D索大10 小时前
【11408学习记录】考研英语长难句拆解三步法:三步拆解2020年真题,攻克阅读难点
笔记·学习·考研·改行学it
好奇龙猫10 小时前
【日语学习-日语知识点小记-构建基础-JLPT-N3阶段-二阶段(32):本階段が終わります】
学习
悠闲漫步者10 小时前
第2章 MCS-51单片机的串口和最小系统(学习笔记)
笔记·学习·51单片机
shenghaide_jiahu10 小时前
数学分析简明教程——6.5
学习
shenghaide_jiahu11 小时前
数学分析简明教程——6.4
学习
爱吃泡芙的小白白11 小时前
Agent学习——路由链
学习·agent·路由链
wdfk_prog11 小时前
[Linux]学习笔记系列 -- [fs]buffer
linux·笔记·学习