Skip to content

[SPARK-2871] [PySpark] add key argument for max(), min() and top(n) #2094

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 27 additions & 17 deletions python/pyspark/rdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,23 +810,37 @@ def func(iterator):

return self.mapPartitions(func).fold(zeroValue, combOp)

def max(self):
def max(self, key=None):
"""
Find the maximum item in this RDD.

>>> sc.parallelize([1.0, 5.0, 43.0, 10.0]).max()
@param key: A function used to generate key for comparing

>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0
"""
return self.reduce(max)
if key is None:
return self.reduce(max)
return self.reduce(lambda a, b: max(a, b, key=key))

def min(self):
def min(self, key=None):
"""
Find the minimum item in this RDD.

>>> sc.parallelize([1.0, 5.0, 43.0, 10.0]).min()
1.0
@param key: A function used to generate key for comparing

>>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])
>>> rdd.min()
2.0
>>> rdd.min(key=str)
10.0
"""
return self.reduce(min)
if key is None:
return self.reduce(min)
return self.reduce(lambda a, b: min(a, b, key=key))

def sum(self):
"""
Expand Down Expand Up @@ -924,7 +938,7 @@ def mergeMaps(m1, m2):
return m1
return self.mapPartitions(countPartition).reduce(mergeMaps)

def top(self, num):
def top(self, num, key=None):
"""
Get the top N elements from a RDD.

Expand All @@ -933,20 +947,16 @@ def top(self, num):
[12]
>>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)
[6, 5]
>>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str)
[4, 3, 2]
"""
def topIterator(iterator):
q = []
for k in iterator:
if len(q) < num:
heapq.heappush(q, k)
else:
heapq.heappushpop(q, k)
yield q
yield heapq.nlargest(num, iterator, key=key)

def merge(a, b):
return next(topIterator(a + b))
return heapq.nlargest(num, a + b, key=key)

return sorted(self.mapPartitions(topIterator).reduce(merge), reverse=True)
return self.mapPartitions(topIterator).reduce(merge)

def takeOrdered(self, num, key=None):
"""
Expand Down