spark RDD转换算子 map 、mapPartitions、mapPartitionsWithIndex

概念:

map:通过函数func传递源的每个元素来形成一个新的分布式数据集

mapPartitions:与map类似,但是在RDD的每个分区(块)上分别运行,所以func在类型T的RDD上运行时必须是Iterator <T> => Iterator <U>类型。

mapPartitionsWithIndex:类似于mapPartitions,但也提供func代表分区索引的整数值,所以func在T型RDD上运行时必须是(Int,Iterator <T>)=> Iterator <U>类型。

官网案例:

map:

>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())

[('a', 1), ('b', 1), ('c', 1)]

从案例里面看出,map是针对每个元素操作的,返回的数据集和原始数据数量上保持一致。

mapPartitions:

>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()

[3, 7]

从案例可以看出,是将分区中的数据都计算完毕后返回,减少了数据访问的次数。提高了效率。

mapPartitionsWithIndex:

>>> rdd = sc.parallelize([1, 2, 3, 4], 4)
>>> def f(splitIndex, iterator): yield splitIndex
>>> rdd.mapPartitionsWithIndex(f).sum()

6

从案例来看,索引是从0开始的,可以通过索引知道数据在哪个分区里面跑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值