有没有一种方法可以使用numpy.percentile函数计算加权百分位数?或者是否有其他的Python函数可用于计算加权百分位数?
谢谢!
有没有一种方法可以使用numpy.percentile函数计算加权百分位数?或者是否有其他的Python函数可用于计算加权百分位数?
谢谢!
不幸的是,numpy并没有内置所有加权函数,但你总可以自己组合一些。
def weight_array(ar, weights):
zipped = zip(ar, weights)
weighted = []
for a, w in zipped:
for j in range(w):
weighted.append(a)
return weighted
np.percentile(weight_array(ar, weights), 25)
np.percentile(Counter(dict(zip(ar, weights)).elements()), 25)
。您需要从collections
中导入Counter
,并且它在ar
中有重复的键时表现不佳,但是Counter().elements()
很好用! - colcarroll这是我的解决方案:
def my_weighted_perc(data,perc,weights=None):
if weights==None:
return nanpercentile(data,perc)
else:
d=data[(~np.isnan(data))&(~np.isnan(weights))]
ix=np.argsort(d)
d=d[ix]
wei=weights[ix]
wei_cum=100.*cumsum(wei*1./sum(wei))
return interp(perc,wei_cum,d)