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

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

 结果:


http://www.kler.cn/a/614003.html

相关文章:

  • TDengine 中的系统信息统计
  • 【leetcode hot 100 45】跳跃游戏Ⅱ
  • SpringBoot 7 种实现 HTTP 调用的方式
  • Maven 多模块项目(如微服务架构)中,父 POM(最外层) 和 子模块 POM(具体业务模块)的区别和联系
  • 深入理解 Linux 基础 IO:从文件操作到缓冲区机制
  • 如何利用 CSS 的clip - path属性创建不规则形状的元素,应用场景有哪些?
  • ngx_http_core_init_main_conf
  • windows免密ssh登录linux
  • 项目代码第10讲【数据库运维知识——如何优化数据库查询效率?】:各种日志查看;主从复制;分库分表(MyCat);读写分离;区别数据分区、分表、分库
  • uni-app AES 加密
  • 判断质数及其优化方法
  • unity 做一个圆形分比图
  • 内网服务器无法通过公网地址访问映射到公网的内网服务
  • 使用事件监听器来处理并发环境中RabbitMQ的同步响应问题
  • 代码随想录算法训练营--打卡day1
  • maxDataPointsPerRollingArg must be at least 1
  • vue(1-45)
  • 方法指南:利用边缘计算实现低延迟直播流媒体服务
  • 如何用Java拆分PDF文件(教程)
  • 【C++数据库】SQLite3数据库连接与操作