【问题标题】:Rdd lambda function confusion around rows vs columns围绕行与列的 Rdd lambda 函数混淆
【发布时间】: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


【解决方案1】:

好的,当您执行第一步时:

rdd2 = spark.sparkContext.parallelize([
(33, 385), (26, 2), (55, 221), (40, 465), (68, 21), (59, 318), (37, 220), (54, 307)
])

# Simple count example
# Make a key value pair like ((age, numFriends), 1) 
# Now your key is going to be (age, numFriends) and value is going to be 1
# When you say reduceByKey, it will add up all values for the same key
rdd3  = rdd2.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x+y)

totalsByAge = rdd2.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y:(x[0] + y[0], x[1] + y[1]))

在上述情况下,您正在做的是:

  • 创建(age, (numFriends, 1))的成对RDD
  • reduceByKey 在哪里,你取xy 并对其执行(x[0] + y[0], x[1] + y[1])。 在这里,您的 x 是 RDD 的一个元素,y 是另一个元素(但按年龄分组)
  • 您创建了年龄组(因为第一个元素是您的键,即age),将x[0]y[0] 相加,每个年龄组的numFriends 相加,x[1]y[1] 相加添加我们在第一步中添加的计数器mapValues 每个年龄段。

【讨论】:

  • 谢谢!我一直在使用 spark 数据框。我想我会尝试一下 RDD,但它们真的很令人困惑 :) 感谢您的帮助
  • @kikee1222 一旦你了解了 map 和 reduce 的工作原理,它就会变得非常容易。但请放心,如果使用得当,Spark 数据帧是非常优化和高效的。您应该尽可能使用它们。
猜你喜欢
  • 1970-01-01
  • 2013-03-26
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多