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

结果:

相关推荐
一条小小yu2 小时前
基于数据库唯一索引 + 过期时间的分布式锁
学习
传奇开心果编程2 小时前
【ArkUI 练中学】第15课:UI 界面设计与实战
学习·ui·华为·harmonyos
传奇开心果编程4 小时前
【springboot基础语法学与练】第 1 课:从零开始
java·spring boot·后端·学习
扶风ff4 小时前
练题簿小程序:家庭在线练题,课后复习更简单
学习·小程序
传奇开心果编程4 小时前
【Flutter入门练中学】第2课:布局系统
学习·flutter·ui
彧azz4 小时前
Linux 网络编程学习总结
linux·网络·笔记·学习·面试
一尘之中5 小时前
指挥控制中心与指控系统:概念、应用、厂商与DDS技术全景
学习·架构·ai写作
一条破秋裤5 小时前
测试A学习顺序
学习
传奇开心果编程5 小时前
【Jetpack Compose基础语法学与练】第8课 rememberSaveable,页面旋转/系统重建保留状态
android·学习·ui·kotlin·android jetpack
迪丽热爱6 小时前
多媒体应用16-830(补)
学习