Нет встроенной функции, но вы можете легко написать ее, используя существующие компоненты.
# In Spark < 2.4 replace array_sort with sort_array
# Thanks to @RaphaelRoth for pointing that out
from pyspark.sql.functions import array, array_sort, floor, col, size
from pyspark.sql import Column
def percentile(p, *args):
def col_(c):
if isinstance(c, Column):
return c
elif isinstance(c, str):
return col(c)
else:
raise TypeError("args should str or Column, got {}".format(type(c)))
xs = array_sort(array(*[col_(x) for x in args]))
n = size(xs)
h = (n - 1) * p
i = floor(h).cast("int")
x0, x1 = xs[i], xs[i + 1]
return x0 + (h - i) * (x1 - x0)
Пример использования:
df.withColumn("median", percentile(0.5, *df.columns)).show()
+---+---+---+------+
| a| b| c|median|
+---+---+---+------+
| 1| 2| 3| 2.0|
| 1| 4|100| 4.0|
| 20| 30| 50| 30.0|
+---+---+---+------+
То же самое можно сделать в Scala :
import org.apache.spark.sql.functions._
import org.apache.spark.sql.Column
def percentile(p: Double, args: Column*) = {
val xs = array_sort(array(args: _*))
val n = size(xs)
val h = (n - 1) * p
val i = floor(h).cast("int")
val (x0, x1) = (xs(i), xs(i + 1))
x0 + (h - i) * (x1 - x0)
}
val df = Seq((1, 2, 3), (1, 4, 100), (20, 30, 50)).toDF("a", "b", "c")
df.withColumn("median", percentile(0.5, $"a", $"b", $"c")).show
+---+---+---+------+
| a| b| c|median|
+---+---+---+------+
| 1| 2| 3| 2.0|
| 1| 4|100| 4.0|
| 20| 30| 50| 30.0|
+---+---+---+------+
Только в Python вы также можете рассмотреть векторизованный UDF - в общем, он, скорее всего, будет медленнее, чем встроенные функции, но лучше, чем векторизованный udf
:
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark.sql.types import DoubleType
import pandas as pd
import numpy as np
def pandas_percentile(p=0.5):
assert 0 <= p <= 1
@pandas_udf(DoubleType())
def _(*args):
return pd.Series(np.percentile(args, q = p * 100, axis = 0))
return _
df.withColumn("median", pandas_percentile(0.5)("a", "b", "c")).show()
+---+---+---+------+
| a| b| c|median|
+---+---+---+------+
| 1| 2| 3| 2.0|
| 1| 4|100| 4.0|
| 20| 30| 50| 30.0|
+---+---+---+------+