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()

结果:

相关推荐
淘矿人2 分钟前
2026年4月-DeepSeek V4 vs GPT-5.5深度对比测评:weelinking一键切换实测
服务器·数据库·人工智能·python·gpt·学习·php
一只机电自动化菜鸟6 分钟前
一建机电备考笔记(27)测量技术—仪器(含考频+题型)
经验分享·笔记·学习·职场和发展·求职招聘·课程设计
xiaoxiaoxiaolll19 分钟前
《Light: Science & Applications》SSH模型能带首次在光子芯片上直接读出:混合频率架构赋能拓扑量子模拟
学习
Be for thing19 分钟前
Android Studio 常用快捷键总结
android·学习
茜子.Java34 分钟前
postman 进阶使用教程
学习
爱上好庆祝40 分钟前
学习js的第四天
前端·css·学习·html·css3·js
d111111111d41 分钟前
UAER问题+修复小bug
前端·javascript·笔记·stm32·单片机·嵌入式硬件·学习
星幻元宇VR44 分钟前
VR校园安全学习机:让安全意识从“心”出发
科技·学习·安全·vr·虚拟现实
烤麻辣烫1 小时前
算法--二分搜索
java·开发语言·学习·算法·intellij-idea
代码丰1 小时前
Github高赞项目50K learn-claude-code 的学习笔记总结
笔记·学习·github