Spark Scala:用户定义的计算中位数的聚合函数

时间:2016-06-02 11:12:21

标签: scala apache-spark group-by median user-defined-aggregate

我正试图找到一种方法来计算给定数据帧的中位数。

val df = sc.parallelize(Seq(("a",1.0),("a",2.0),("a",3.0),("b",6.0), ("b", 8.0))).toDF("col1", "col2")

+----+----+
|col1|col2|
+----+----+
|   a| 1.0|
|   a| 2.0|
|   a| 3.0|
|   b| 6.0|
|   b| 8.0|
+----+----+

现在我想这样做:
df.groupBy("col1").agg(calcmedian("col2"))

结果应如下所示:

+----+------+
|col1|median|
+----+------+
|   a|   2.0|
|   b|   7.0|
+----+------+` 

因此calcmedian()必须是UDAF,但问题是,UDAF的“evaluate”方法只需要一行,但我需要整个表来对值进行排序并返回中位数...

// Once all entries for a group are exhausted, spark will evaluate to get the final result  
def evaluate(buffer: Row) = {...}

这有可能吗?或者还有另一个不错的解决方法吗?我想强调,我知道如何计算“一组”数据集的中位数。但是我不想在“foreach”循环中使用这个算法,因为这是低效的!

谢谢!

编辑:

这就是我到目前为止所做的:

object calcMedian extends UserDefinedAggregateFunction {
    // Schema you get as an input 
    def inputSchema = new StructType().add("col2", DoubleType)
    // Schema of the row which is used for aggregation
    def bufferSchema = new StructType().add("col2", DoubleType)
    // Returned type
    def dataType = DoubleType
    // Self-explaining 
    def deterministic = true
    // initialize - called once for each group
    def initialize(buffer: MutableAggregationBuffer) = {
        buffer(0) = 0.0
    }

    // called for each input record of that group
    def update(buffer: MutableAggregationBuffer, input: Row) = {
        buffer(0) = input.getDouble(0)
    }
    // if function supports partial aggregates, spark might (as an optimization) comput partial results and combine them together
    def merge(buffer1: MutableAggregationBuffer, buffer2: Row) = {
      buffer1(0) = input.getDouble(0)   
    }
    // Once all entries for a group are exhausted, spark will evaluate to get the final result
    def evaluate(buffer: Row) = {
        val tile = 50
        var median = 0.0

        //PROBLEM: buffer is a Row --> I need DataFrame here???
        val rdd_sorted = buffer.sortBy(x => x)
        val c = rdd_sorted.count()
        if (c == 1){
            median = rdd_sorted.first()                
        }else{
            val index = rdd_sorted.zipWithIndex().map(_.swap)
            val last = c
            val n = (tile/ 100d) * (c*1d)
            val k = math.floor(n).toLong       
            val d = n - k
            if( k <= 0) {
                median = rdd_sorted.first()
            }else{
                if (k <= c){
                    median = index.lookup(last - 1).head
                }else{
                    if(k >= c){
                        median = index.lookup(last - 1).head
                    }else{
                        median = index.lookup(k-1).head + d* (index.lookup(k).head - index.lookup(k-1).head)
                    }
                }
            }
        }
    }   //end of evaluate

1 个答案:

答案 0 :(得分:5)

试试这个:

import org.apache.spark.functions._

val result = data.groupBy("col1").agg(callUDF("percentile_approx", col("col2"), lit(0.5)))