当前位置: 首页 > news >正文

pyspark学习rdd处理数据方法——学习记录

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

 结果:

相关文章:

  • 3.22模拟面试
  • kotlin 函数引用
  • 通过webrtc+canvas+css实现简单的电脑滤镜拍照效果
  • 同旺科技USB to SPI 适配器 ---- 指令循环发送功能
  • Baklib智能内容推荐的核心是什么?
  • Vue3前端开发:组件化设计与状态管理
  • 文献分享: XTR——优化Token级检索的高效多向量模型
  • nginx5天时间从0到熟练掌握学习计划
  • 坐标变换其一 ccf-csp 2023-9-1
  • 自定义reset50模型转换到昇腾om
  • dijkstra(堆优化版)
  • 长沙搞么子
  • 数字证书 与 数字签名 介绍
  • C语言 转义字符
  • 从GTC2025首次量子日看英伟达量子AI融合算力网络前景与趋势
  • Deepseek训练成AI图片生成机器人
  • 线程的概念和控制
  • Kotlin 协程基础知识汇总(一)
  • vue3:十一、主页面布局(进入指定菜单页面,默认锁定到左侧菜单)
  • 【MySQL】全面学习数据库查询技巧:查询指令深度学习指南
  • 2025年度中国青年五四奖章暨新时代青年先锋奖评选揭晓
  • 中国空间站首批在轨繁育果蝇即将返回地球,有望获得多项科学成果
  • 五一假期上海地铁部分线路将延时运营,这些调整请查收
  • 五月院线片单:就看五一档表现了
  • 伊朗港口爆炸死亡人数升至70人
  • BNEF:亚洲、中东和非洲是电力基础设施投资的最大机会所在