3 回答

TA貢獻1946條經(jīng)驗 獲得超4個贊
火花2.0+:
approxQuantile
Python:
df.approxQuantile("x", [0.5], 0.25)
斯卡拉:
df.stat.approxQuantile("x", Array(0.5), 0.25)
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
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 < sample <= 1 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)
語言獨立 (蜂箱):
HiveContext
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

TA貢獻1802條經(jīng)驗 獲得超10個贊
/** * Gets the nth percentile entry for an RDD of doubles * * @param inputScore : Input scores consisting of a RDD of doubles * @param percentile : The percentile cutoff required (between 0 to 100), e.g 90%ile of [1,4,5,9,19,23,44] = ~23. * It prefers the higher value when the desired quantile lies between two data points * @return : The number best representing the percentile in the Rdd of double */ def getRddPercentile(inputScore: RDD[Double], percentile: Double): Double = { val numEntries = inputScore.count().toDouble val retrievedEntry = (percentile * numEntries / 100.0 ).min(numEntries).max(0).toInt inputScore .sortBy { case (score) => score } .zipWithIndex() .filter { case (score, index) => index == retrievedEntry } .map { case (score, index) => score } .collect()(0) }
添加回答
舉報