Pyspark RDDReducebyKey()

问题描述 投票:0回答:1
`Hi I am trying to understand where is the problem in my code.


#code 
rdd_avg=sc.parallelize([("a",10),("b",15),("c",20),("a",8)])
rdd_sp1=rdd_avg.map(lambda x: (x,1))
rdd_sp1.collect()
rdd_sp2=rdd_sp1.reduceByKey(lambda a,b:(a[0]+b[0],a[1]+b[1]))
rdd_sp2.collect()
`

#输出 我得到的输出是

[(('c', 20), 1), (('a', 10), 1), (('b', 15), 1), (('a', 8), 1)]

但我正在努力得到。

[(('c', 20), 1), (('a', 18), 2), (('b', 15), 1)]

python pyspark rdd
1个回答
0
投票

你的问题是元组的第一个元素必须是

key
,第二个元素是
value
。在您的示例中,当您执行第一个
map
(
rdd_avg.map(lambda x: (x,1))
) 时,您将使用孔元组作为键。所以这些是你的钥匙:
('c', 20)
('a', 10)
('b', 15)
('a', 8)
。请注意,键
('a', 10)
与键
('a', 8)
不同。您的按键应该是
'a'
'b'
'c'

这是修复的代码:

>>> rdd = sc.parallelize([("a",10), ("b",15), ("c",20),("a",8)])
>>> # the first element of the tuple is x[0], not x
>>> rdd_sp1 = rdd.map(lambda x: (x[0], (x[1], 1)))
>>> rdd_sp1.collect()
[('a', (10, 1)), ('b', (15, 1)), ('c', (20, 1)), ('a', (8, 1))]

注意现在元组的第一个元素是键,而不是元组

>>> rdd_sp2 = rdd_sp1.reduceByKey(lambda a, b: (a[0] + b[0], a[1] + b[1]))
>>> rdd_sp2.collect()
[('b', (15, 1)), ('c', (20, 1)), ('a', (18, 2))]

解决了按键问题后,我们可以通过按键有效减少

>>> rdd_avg = rdd_sp2.map(lambda x: (x[0], x[1][0] / x[1][1]))
>>> rdd_avg.collect()
[('b', 15.0), ('c', 20.0), ('a', 9.0)]
© www.soinside.com 2019 - 2024. All rights reserved.