Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python scipy百分位数的加权版本_Python_Numpy_Scipy - Fatal编程技术网

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.