pyspark RDD基本操作

本文介绍了PySpark中RDD的基本操作,包括转换运算如map、filter等,以及动作运算如count、reduce等,还涉及到了key-values形式的数据处理。
摘要由CSDN通过智能技术生成

RDD转换运算

# 创建intRDD
intRDD = sc.parallelize([3,1,2,5,5,6])
intRDD.collect()
[3, 1, 2, 5, 5, 6]
# 创建stringRDD
stringRDD = sc.parallelize(['apple','pen','banana'])
stringRDD.collect()
['apple', 'pen', 'banana']
# map 对每个元素都进行运算操作
def addOne(x):
    return (x*3)
intRDD.map(addOne).collect()
intRDD.map(lambda x:x+1).collect()
stringRDD.map(lambda x:'first:'+x).collect()
[9, 3, 6, 15, 18]
[4, 2, 3, 6, 7]
['first:apple', 'first:pen', 'first:banana']
# filter数字运算,筛选
intRDD.filter(lambda x: x>2).collect()
intRDD.filter(lambda x:0<x<5).collect()
intRDD.filter(lambda x:x>=5 or x<3).collect()
stringRDD.filter(lambda x: 'a' in x).collect()
[3, 5, 6]
[3, 1, 2]
[1, 2, 5, 6]
['apple', 'banana']
# distinct 删除重复元素
intRDD.distinct().collect()
# randomSplit 可以将整个集合元素以随机数的方式按照比例分为多个RDD
sRDD = intRDD.randomSplit([0.4,0.6])
sRDD[0].collect()
sRDD[1].collect()
# groupby可以按照传入的匿名函数规则将数据分为多个List
gRDD = intRDD.groupBy(lambda x: "even" if(x%2 == 0) else "odd").collect()
gRDD
[1, 5, 2, 6, 3]
[2, <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值