pyspark RDD reduce、reduceByKey、reduceByKeyLocally用法

一、reduce

Reduces the elements of this RDD using the specified commutative and associative binary operator. Currently reduces partitions locally.

a=sc.parallelize([1,2,3,4,5],2).reduce(add)
print(a)

a=sc.parallelize((2 for _ in range(10))).map(lambda x:1).cache().reduce(add)
print(a)

二、reduceByKey(func, numPartitions=None, partitionFunc=)
Merge the values for each key using an associative and commutative reduce function.

This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a “combiner” in MapReduce.

Output will be partitioned with numPartitions partitions, or the default parallelism level if numPartitions is not specified. Default partitioner is hash-partition.
按照k值操作V值,返回k-v列表

def add1(a, b):

    print("*"*55)
    print(a)
    print(b)
    return a + b+100

rdd=sc.parallelize([('a',1),('b',100),('a',300),('b',3),('a',200)])

a=sorted(rdd.reduceByKey(add1).collect())
print(a)

在这里插入图片描述

三、reduceByKeyLocally(func)
Merge the values for each key using an associative and commutative reduce function, but return the results immediately to the master as a dictionary.
同reduceByKey,但是返回一个字典

def add1(a, b):

    print("*"*55)
    print(a)
    print(b)
    return a + b


rdd=sc.parallelize([('a',1),('b',100),('a',300),('b',3),('a',200)])
a=rdd.reduceByKeyLocally(add1)
print("%"*33)
print(a)
print(type(a))

print(a.items())
print(sorted(a.items()))

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值