How to use approxQuantile by group?

余生颓废 提交于 2019-12-19 04:15:34

问题


Spark has SQL function percentile_approx(), and its Scala counterpart is df.stat.approxQuantile().

However, the Scala counterpart cannot be used on grouped datasets, something like df.groupby("foo").stat.approxQuantile(), as answered here: https://stackoverflow.com/a/51933027.

But it's possible to do both grouping and percentiles in SQL syntax. So I'm wondering, maybe I can define an UDF from SQL percentile_approx function and use it on my grouped dataset?


回答1:


While you cannot use approxQuantile in an UDF, and you there is no Scala wrapper for percentile_approx it is not hard to implement one yourself:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.Column
import org.apache.spark.sql.catalyst.expressions.aggregate.ApproximatePercentile


object PercentileApprox {
  def percentile_approx(col: Column, percentage: Column, accuracy: Column): Column = {
    val expr = new ApproximatePercentile(
      col.expr,  percentage.expr, accuracy.expr
    ).toAggregateExpression
    new Column(expr)
  }
  def percentile_approx(col: Column, percentage: Column): Column = percentile_approx(
    col, percentage, lit(ApproximatePercentile.DEFAULT_PERCENTILE_ACCURACY)
  )
}

Example usage:

import PercentileApprox._

val df = (Seq.fill(100)("a") ++ Seq.fill(100)("b")).toDF("group").withColumn(
  "value", when($"group" === "a", randn(1) + 10).otherwise(randn(3))
)

df.groupBy($"group").agg(percentile_approx($"value", lit(0.5))).show
+-----+------------------------------------+
|group|percentile_approx(value, 0.5, 10000)|
+-----+------------------------------------+
|    b|                -0.06336346702250675|
|    a|                   9.818985618591595|
+-----+------------------------------------+
df.groupBy($"group").agg(percentile_approx($"value", typedLit(Seq(0.1, 0.25, 0.75, 0.9)))).show(false)
+-----+----------------------------------------------------------------------------------+
|group|percentile_approx(value, [0.1,0.25,0.75,0.9], 10000)                              |
+-----+----------------------------------------------------------------------------------+
|b    |[-1.2098351202406483, -0.6640768986666159, 0.6778253126144265, 1.3255676906697658]|
|a    |[8.902067202468098, 9.290417382259626, 10.41767257153993, 11.067087075488068]     |
+-----+----------------------------------------------------------------------------------+

Once this is on the JVM classpath you can also add PySpark wrapper, using logic similar to built-in functions.



来源:https://stackoverflow.com/questions/53548964/how-to-use-approxquantile-by-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!