火花2.0+:

你可以用approxQuantile实现Greenwald-Khanna算法:

Python:df.approxQuantile("x", [0.5], 0.25)

斯卡拉:df.stat.approxQuantile("x", Array(0.5), 0.25)

其中最后一个参数是一个相对错误。次数越少,计算结果越准确,计算量越大。

星火2.2(火花-14352)它支持对多列的估计:df.approxQuantile(["x", "y", "z"], [0.5], 0.25)

和df.approxQuantile(Array("x", "y", "z"), Array(0.5), 0.25)

火花<2.0

Python

正如我在评论中提到的,这很可能不值得大惊小怪。如果数据相对较小,比如在您的情况下,那么只需在本地收集和计算中值:import numpy as np

np.random.seed(323)rdd = sc.parallelize(np.random.randint(1000000, size=700000))%time np.median(rdd.collect())np.array(rdd.collect()).nbytes

在我几年前的电脑上,它需要大约0.01秒的时间和大约5.5MB的内存。

如果数据要大得多,排序将是一个限制因素,因此,与其获得确切的值,不如在本地进行采样、收集和计算。但是,如果你真的想让一个人使用星火,这样的事情应该能起作用(如果我什么都没搞砸的话):from numpy import floorimport timedef quantile(rdd, p, sample=None, seed=None):

"""Compute a quantile of order p ∈ [0, 1]

:rdd a numeric rdd

:p quantile(between 0 and 1)

:sample fraction of and rdd to use. If not provided we use a whole dataset

:seed random number generator seed to be used with sample

"""

assert 0 <= p <= 1

assert sample is None or 0 

seed = seed if seed is not None else time.time()

rdd = rdd if sample is None else rdd.sample(False, sample, seed)

rddSortedWithIndex = (rdd.

sortBy(lambda x: x).

zipWithIndex().

map(lambda (x, i): (i, x)).

cache())

n = rddSortedWithIndex.count()

h = (n - 1) * p

rddX, rddXPlusOne = (

rddSortedWithIndex.lookup(x)[0]

for x in int(floor(h)) + np.array([0L, 1L]))

return rddX + (h - floor(h)) * (rddXPlusOne - rddX)

还有一些测试:np.median(rdd.collect()), quantile(rdd, 0.5)## (500184.5, 500184.5)np.percentile(rdd.collect(), 25), quantile(rdd, 0.25)## (250506.75, 250506.75)np.percentile(rdd.collect(), 75), quantile(rdd, 0.75)(750069.25, 750069.25)

最后,让我们定义中位数:from functools import partial

median = partial(quantile, p=0.5)

到目前为止还不错,但是它需要4.66秒的本地模式,没有任何网络通信。也许有办法改善这一点,但为什么还要费心呢?

语言独立 (蜂箱):

如果你用HiveContext您也可以使用HiveUDAFs。具有积分值:rdd.map(lambda x: (float(x), )).toDF(["x"]).registerTempTable("df")sqlContext.sql("SELECT percentile_approx(x, 0.5) FROM df")

具有连续值:sqlContext.sql("SELECT percentile(x, 0.5) FROM df")

在……里面percentile_approx您可以传递另一个参数,该参数确定要使用的多个记录。

Logo

GitCode AI社区是一款由 GitCode 团队打造的智能助手,AI大模型社区、提供国内外头部大模型及数据集服务。

更多推荐