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

结果:

相关推荐
:mnong8 分钟前
通过手写识别数字可视化学习卷积神经网络原理
人工智能·学习·cnn
AI视觉网奇1 小时前
Epic linux 打包。
笔记·学习·ue5
biuyyyxxx1 小时前
Power Query学习笔记(一)
笔记·学习
佳哥的技术分享3 小时前
Function<T, R> 中 apply,compose, andThen 方法总结
java·学习·r语言
阳明Coding4 小时前
golang从入门到通天—数据库操作(gorm框架使用)(最简单最详细的golang学习笔记)
笔记·学习·golang
AI视觉网奇4 小时前
ue5 开发 web socket server 实战2026
c++·学习·ue5
嗯嗯=4 小时前
STM32单片机学习篇6
stm32·单片机·学习
2301_797312264 小时前
学习Java42天
java·开发语言·学习
找了一圈尾巴4 小时前
智能体自演进框架-ACE(论文学习)
学习·提示词
ValidationExpression4 小时前
学习:企业标准的容器化 CI,CD 发布流程
学习·ci/cd