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

结果:

相关推荐
Chloeis Syntax42 分钟前
MySQL初阶学习日记(1)--- 数据库的基本操作
数据库·学习·mysql
musenh2 小时前
css样式学习
css·学习·css3
Larry_Yanan2 小时前
QML学习笔记(五十)QML与C++交互:QML中单例C++对象
开发语言·c++·笔记·qt·学习·ui·交互
im_AMBER2 小时前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
Nan_Shu_6143 小时前
学习:JavaScript(5)
开发语言·javascript·学习
民乐团扒谱机3 小时前
实验室安全教育与管理平台学习记录(八)特种设备安全
学习·安全
喜欢吃燃面4 小时前
C++:哈希表
开发语言·c++·学习
初圣魔门首席弟子5 小时前
C++ STL list 容器学习笔记:双向链表的 “小火车“ 操控指南
c++·windows·笔记·学习
2301_796512525 小时前
Rust编程学习 - 如何学习有关函数和闭包的高级特性,这包括函数指针以及返回闭包
服务器·学习·rust
LBuffer5 小时前
破解入门学习笔记题三十四
java·笔记·学习