Weighted percentile using numpy

前端 未结 12 2223
一个人的身影
一个人的身影 2020-12-01 03:28

Is there a way to use the numpy.percentile function to compute weighted percentile? Or is anyone aware of an alternative python function to compute weighted percentile?

12条回答
  •  悲&欢浪女
    2020-12-01 04:25

    here my solution:

    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)
    

    it simply calculates the weighted CDF of the data and then it uses to estimate the weighted percentiles.

提交回复
热议问题