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

结果:

相关推荐
沉默-_-8 分钟前
微信小程序网络请求 wx.request 详解
网络·学习·微信小程序·小程序
嗯嗯=24 分钟前
STM32单片机学习篇5
stm32·单片机·学习
头疼的程序员1 小时前
计算机网络:自顶向下方法(第七版)第二章 学习分享(二)
学习·计算机网络
沉默-_-2 小时前
微信小程序页面配置详解
学习·微信小程序·apache·微信开发者工具
北京云帆互联科技2 小时前
云帆学习考试系统更新说明v8.8.0
学习·考试系统·高校考试系统
Quintus五等升2 小时前
深度学习③|分类任务—AlexNet
人工智能·经验分享·深度学习·神经网络·学习·机器学习·cnn
张心独酌3 小时前
学习Rust:实现RESTful 任务管理 API(Todo API)
学习·rust·restful
反向跟单策略3 小时前
如何正确看待期货反向跟单策略?
大数据·人工智能·学习·数据分析·区块链
QiZhang | UESTC3 小时前
学习日记day65
学习
leaves falling3 小时前
C 语言-文件操作学习
学习