【发布时间】:2019-10-20 18:22:51
【问题描述】:
我有一个 spark RDD(下面的完整代码),我有点困惑。
给定输入数据:
385 | 1
291 | 2
如果我有以下 lambda 函数,为什么在 reduceByKey 中有 x[0]+y[0] = 385+291? X 和 Y 肯定与 RDD 的不同列有关吗?还是我认为这意味着他们指的是
totalsByAge = rdd2.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y:(x[0] + y[0], x[1] + y[1]))
完整代码:
import findspark
findspark.init()
import pyspark
#UserID | Name | Age | Num_Friends
#r before the filepath converts it to a raw string
lines = sc.textFile(r"c:\Users\kiera\Downloads\fakefriends.csv")
#For each line in the file, split it at the comma
#split 2 is the age
#Split 3 is the number of friends
def splitlines(line):
fields = line.split(',')
age = int(fields[2])
numFriends = int(fields[3])
return (age, numFriends)
rdd2 = lines.map(splitlines)
totalsByAge = rdd2.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y:(x[0] + y[0], x[1] + y[1]))
rdd2 看起来像这样
[(33, 385),
(26, 2),
(55, 221),
(40, 465),
(68, 21),
(59, 318),
(37, 220),
(54, 307)....
【问题讨论】:
-
你的意思是在最后一行使用
rdd2吗? -
是的,抱歉,这是一个愚蠢的错误 :) 我想我只是对 Lambda 函数的工作原理感到困惑。为什么 X[0] + y[0] 不是 x[0]+x[1]
标签: python python-3.x apache-spark lambda pyspark