def weighted_quantile(x, weights, quantile):
I = np.argsort(x)
sort_x = x[I]
sort_w = weights[I]
acum_w = np.add.accumulate(sort_w)
norm_w = (acum_w - 0.5*sort_w)/acum_w[-1]
interpq = np.searchsorted(norm_w, [quantile])[0]
if interpq == 0:
return sort_x[0]
elif interpq == len(x):
return sort_x[-1]
else:
tmp1 = (norm_w[interpq] - quantile)/(norm_w[interpq] - norm_w[interpq-1])
tmp2 = (quantile - norm_w[interpq-1])/(norm_w[interpq] - norm_w[interpq-1])
assert tmp1>=0 and tmp2>=0 and tmp1<=1 and tmp2<=1
return sort_x[interpq-1]*tmp1 + sort_x[interpq]*tmp2
评论列表
文章目录