Python scipy百分位数的加权版本
我想把重量传给你。例如:Python scipy百分位数的加权版本,python,numpy,scipy,Python,Numpy,Scipy,我想把重量传给你。例如: from scipy import stats a = [1, 2, 3, 4] val = 3 stats.percentileofscore(a, val) weights = [2, 2, 3, 3] weightedpercentileofscore(a, val, weights) 返回75,因为a中75%的值位于val3或以下 我想添加权重,例如: from scipy import stats a = [1, 2, 3, 4] val = 3 stat
from scipy import stats
a = [1, 2, 3, 4]
val = 3
stats.percentileofscore(a, val)
weights = [2, 2, 3, 3]
weightedpercentileofscore(a, val, weights)
返回75,因为a
中75%的值位于val
3或以下
我想添加权重,例如:
from scipy import stats
a = [1, 2, 3, 4]
val = 3
stats.percentileofscore(a, val)
weights = [2, 2, 3, 3]
weightedpercentileofscore(a, val, weights)
应该返回70,因为(2+2+3)/(2+2+3+3)=7/10的权重落在3或以下
这也适用于十进制权重和大权重,因此仅扩展数组并不理想
是相关的,但计算百分位(例如,要求第10个百分位值),而不是某个值的特定百分位。这应该可以完成这项工作
import numpy as np
def weighted_percentile_of_score(a, weights, score, kind='weak'):
npa = np.array(a)
npw = np.array(weights)
if kind == 'rank': # Equivalent to 'weak' since we have weights.
kind = 'weak'
if kind in ['strict', 'mean']:
indx = npa < score
strict = 100 * sum(npw[indx]) / sum(weights)
if kind == 'strict':
return strict
if kind in ['weak', 'mean']:
indx = npa <= score
weak = 100 * sum(npw[indx]) / sum(weights)
if kind == 'weak':
return weak
if kind == 'mean':
return (strict + weak) / 2
a = [1, 2, 3, 4]
weights = [2, 2, 3, 3]
print(weighted_percentile_of_score(a, weights, 3)) # 70.0 as desired.