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

结果:

相关推荐
焜昱错眩..9 分钟前
力扣周赛难题 3906.统计网格路径中好整数的数目——自我拆解学习与分析(数位dp上下界的奇妙)
学习·算法·leetcode·动态规划
空中海10 分钟前
Git-01:基础篇 — 版本控制与日常操作
git·学习
happymaker062619 分钟前
Spring学习日记——DAY06(事务管理)
java·学习·spring
咸甜适中1 小时前
rust语言学习笔记Trait之 From 和 Into (类型转换)
笔记·学习·rust
叶~小兮1 小时前
K8S优先级、Pod驱逐、HPA扩缩容 学习笔记
笔记·学习·kubernetes
babe小鑫1 小时前
2026年IT行业学习数据分析的价值
学习·数据挖掘·数据分析
星恒随风1 小时前
四天学完前端基础三件套(CSS篇)
前端·css·笔记·学习
Hali_Botebie1 小时前
【图卷积网络】GAT(Graph Attention Network,图注意力网络),可学习的打分 + 归一化加权求和’构成了注意力
学习
Hua-Jay1 小时前
OpenCV联合C++/Qt 学习笔记(二十)----Harri角点检测、Shi-Tomas角点检测及亚像素级别角点位置优化
c++·笔记·qt·opencv·学习·计算机视觉
白小沫1 小时前
TortoiseSVN 的每个菜单功能是什么??
笔记·学习