documentation for ^{}(在More About=>;算法部分下)给出了所使用的精确算法。下面是一些python代码,它对平面数组的单个分位数执行此操作,使用bottleneck进行部分排序:import numpy as np
import botteleneck as bn
def quantile(a, prob):
"""
Estimates the prob'th quantile of the values in a data array.
Uses the algorithm of matlab's quantile(), namely:
- Remove any nan values
- Take the sorted data as the (.5/n), (1.5/n), ..., (1-.5/n) quantiles.
- Use linear interpolation for values between (.5/n) and (1 - .5/n).
- Use the minimum or maximum for quantiles outside that range.
See also: scipy.stats.mstats.mquantiles
"""
a = np.asanyarray(a)
a = a[np.logical_not(np.isnan(a))].ravel()
n = a.size
if prob >= 1 - .5/n:
return a.max()
elif prob <= .5 / n:
return a.min()
# find the two bounds we're interpreting between:
# that is, find i such that (i+.5) / n <= prob <= (i+1.5)/n
t = n * prob - .5
i = np.floor(t)
# partial sort so that the ith element is at position i, with bigger ones
# to the right and smaller to the left
a = bn.partsort(a, i)
if i == t: # did we luck out and get an integer index?
return a[i]
else:
# we'll linearly interpolate between this and the next index
smaller = a[i]
larger = a[i+1:].min()
if np.isinf(smaller):
return smaller # avoid inf - inf
return smaller + (larger - smaller) * (t - i)
我只做了一分位数,1d的例子,因为这就是我所需要的。如果你想要几个分位数,那么做完整的排序可能是值得的;要对每个轴进行排序,并且知道你没有任何nan,你需要做的就是在排序中添加一个轴参数,并将线性插值位矢量化。用nans按轴操作会有点棘手。在
该代码给出:
^{pr2}$
matlab代码给出了0.00016905822359999999;区别是{}。(低于机器精度)