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

结果:

相关推荐
寒秋花开曾相惜1 天前
(学习笔记)第四章 处理器体系结构
linux·网络·数据结构·笔记·学习
低代码布道师1 天前
微搭低代码MBA 培训管理系统实战 30——学习卡
学习·低代码·rxjava
南無忘码至尊1 天前
Unity学习90天 - 第 6天 - 学习协程 Coroutine并实现每隔 2 秒生成一波敌人
学习·unity·c#·游戏引擎
LN花开富贵1 天前
【ROS】鱼香ROS2学习笔记二
linux·笔记·python·学习·嵌入式
檬柠wan1 天前
MySQL-数据库增删改查学习
数据库·学习·mysql
minglie11 天前
Zynq 开发中的工程文件管理
学习
炽烈小老头1 天前
【每天学习一点算法 2026/04/16】逆波兰表达式求值
学习·算法
千寻girling1 天前
机器学习 | 线性回归 | 尚硅谷学习
学习·机器学习·线性回归
jasonblog1 天前
对小龙虾openclaw的关注、学习、使用和变化观察
人工智能·学习·ai
Hical_W1 天前
深入学习CPP17_PMR
c++·学习