【问题标题】:How does reduceByKey and mapValues works simultaneously?reduceByKey 和 mapValues 如何同时工作?
【发布时间】:2018-11-21 13:32:56
【问题描述】:

我对 spark 和大数据世界完全陌生。我有一个代码,它实际上创建了一个拆分 CSV 文件并返回两个字段的函数。

然后是 map 函数,我知道它是如何工作的,但我在代码的下一部分(操作发生在 totalsByAge 变量上)感到困惑,mapValues 和 reduceByKey 正在应用。请帮助我了解 reduceByKey 和 mapValues 在这里的工作原理?

def parseLine(line):
fields = line.split(',')
age = int(fields[2])
numFriends = int(fields[3])
return (age,numFriends)

line = sparkCont.textFile("D:\\ResearchInMotion\\ml-100k\\fakefriends.csv")
rdd = line.map(parseLine)
totalsByAge = rdd.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1]))
averagesByAge = totalsByAge.mapValues(lambda x: x[0] / x[1])
results = averagesByAge.collect()
for result in results:
    print(result)

我需要 totalsByAge 变量处理方面的帮助。如果您还可以详细说明对 averagesByAge 所做的操作,那将是很好的,如果缺少任何内容,请告诉我。 p>

【问题讨论】:

    标签: python apache-spark pyspark rdd


    【解决方案1】:

    rdd = line.map(parseLine) 行中,您有一对格式为(age, numFriends) 的值,例如(a_1, n_1), (a_2, n_2), ..., (a_m, n_m)。在rdd.mapValues(lambda x: (x, 1)) 中,您将获得(a_1, (n_1, 1)), (a_2, (n_2, 1)), ..., (a_m, (n_m, 1))

    reduceByKey中,先按key分组,表示同一个age分组在一个组中,你会得到(a_i, iterator over pairs of (n_j, 1) which all n_j has the same age)之类的东西,然后应用归约功能。而减少部分是指每个年龄的所有numFriends相互相加,1s相互相加,其中1s的和表示列表中的项目数。

    因此,在reduceByKey 之后,我们将拥有(a_i, (sum of all numFriends in the list, number of items in the list))。换句话说,外部对的第一个值是age,第二个值是内部对,其第一个值是所有numFriends 的总和,第二个值是项目数。因此,totalsByAge.mapValues(lambda x: x[0] / x[1]) 为每个age 提供了numFriends 的平均值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-30
      • 2017-04-18
      • 2021-07-29
      • 1970-01-01
      • 2015-07-19
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多