使用python spark的RDD中的最后一个元素 [英] last element in RDD using python spark
问题描述
我正在尝试从Spark RDD获取最后的元素信息.我已经分别用(key,value)
对的值对RDD进行了排序.
I am trying to get the last element information from a Spark RDD.
I have sorted the RDD with respective the value of a (key, value)
pair.
我在RDD中的数据
(8, 0.98772733936789858)
(4, 3.0599761935471004)
(2, 3.1913934060593321)
(1, 4.9646263295153013)
(5, 5.3596802463208792)
(7, 5.5829277439661071)
(9, 6.4739040233992258)
(0, 6.9343681509951081)
(6, 7.4699692671955953)
(3, 8.6579764626088771)
我能够使用第一个函数获得第一对(key,value)
对,但无法弄清楚如何获得最后一个对.我可以将(键,值)
对替换为(值,键)
对,并使用.max函数获取所需的数据.但是,还有其他方法可以使用Python Spark从RDD中获取最后一个元素吗?
I am able to get the first (key, value)
pair using the first function, but not able to figure out how to get the last one. I can do a swap of (key, value)
pair to (value, key)
pair and get the required data using .max function. However, is there any other way to get the last element from a RDD using Python spark?
推荐答案
是的,还有其他方法.
根据您在问题中提供的数据集,这里有一些(包括您在内)以及非常非正式的性能排名,该排名基于每种方法在我的计算机上使用一个本地工作线程进行的1000种测试的基础上.
Here are a few (including yours) along with a very informal ranking of performance based on 1000 tests per method with one local worker thread on my machine -- using the dataset you provided in the question.
在此RDD中查找最大项目.
Find the maximum item in this RDD.
output = (
rdd.map(lambda (a, b): (b, a))
.max()
)
这是平均第一快的
排序此RDD,假定该RDD由(键,值)对组成.
Sorts this RDD, which is assumed to consist of (key, value) pairs.
返回此RDD中的第一个元素.
Return the first element in this RDD.
output = (
rdd.map(lambda (a, b): (b, a))
.sortByKey(ascending=False)
.first()
)
这是平均第四快的速度.
This was the 4th fastest on average.
从RDD中获取前N个元素.
Get the top N elements from a RDD.
output = (
rdd.map(lambda (a, b): (b, a))
.top(1)
)
这是平均第三快的
从RDD中获取前N个元素.
Get the top N elements from a RDD.
output = (
rdd.top(1, key=lambda x: x[1])
)
这是平均第二快的速度.
This was the 2nd fastest on average.
您会注意到第4种方法不会交换(键/值).相反,它使用 key (参数为"key",而不是rdd的一部分)扫过rdd,并指定一个参数的功能,该参数用于从可迭代对象的每个元素中提取比较关键字,在这种情况下,比较键是您的(键,值)元组中的第二项,即值.
You'll notice that the 4th method doesn't swap the (key/value)'s. Instead it sweeps over the rdd with key ('key' the argument -- not part of your rdd) specifying a function of one argument that is used to extract a comparison key from each element in the iterable, and in this case the comparison key is the second item in the your (key, value) tuples, i.e. value.
所以方法1(max())非常好.但是...
一旦您位于需要最后一个 n 个元素"的地区(即不仅仅是最后一个元素),那么我会说方法首选4.
这篇关于使用python spark的RDD中的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!