Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

python - Pyspark RDD ReduceByKey Multiple function

I have a PySpark DataFrame named DF with (K,V) pairs. I would like to apply multiple functions with ReduceByKey. For example, I have following three simple functions:

def sumFunc(a,b): return a+b

def maxFunc(a,b): return max(a,b)

def minFunc(a,b): return min(a,b)

When I apply only one function, e.g,, following three work:

DF.reduceByKey(sumFunc)  #works
DF.reduceByKey(maxFunc)  #works
DF.reduceByKey(minFunc)  #works

But, when I apply more than one function, it does not work, e.g., followings do not work.

DF.reduceByKey(sumFunc, maxfunc, minFunc) #it does not work
DF.reduceByKey(sumFunc, maxfunc) #it does not work
DF.reduceByKey(maxfunc, minFunc) #it does not work
DF.reduceByKey(sumFunc, minFunc) #it does not work

I do not want to use groupByKey because it slows down the computation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If input is a DataFrame just use agg:

import pyspark.sql.functions as sqlf

df = sc.parallelize([
   ("foo", 1.0), ("foo", 2.5), ("bar", -1.0), ("bar", 99.0)
]).toDF(["k", "v"])

df.groupBy("k").agg(sqlf.min("v"), sqlf.max("v"), sqlf.sum("v")).show()

## +---+------+------+------+
## |  k|min(v)|max(v)|sum(v)|
## +---+------+------+------+
## |bar|  -1.0|  99.0|  98.0|
## |foo|   1.0|   2.5|   3.5|
## +---+------+------+------+

With RDDs you can use statcounter:

from pyspark.statcounter import StatCounter

rdd = df.rdd
stats = rdd.aggregateByKey(
    StatCounter(), StatCounter.merge, StatCounter.mergeStats
).mapValues(lambda s: (s.min(), s.max(), s.sum()))

stats.collect()
## [('bar', (-1.0, 99.0, 98.0)), ('foo', (1.0, 2.5, 3.5))]

Using your functions you could do something like this:

def apply(x, y, funs=[minFunc, maxFunc, sumFunc]):
    return [f(x_, y_) for f, x_, y_ in zip(*(funs, x, y))]

rdd.combineByKey(lambda x: (x, x, x), apply, apply).collect()
## [('bar', [-1.0, 99.0, 98.0]), ('foo', [1.0, 2.5, 3.5])]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...