【问题标题】:Weighted version of scipy percentileofscorescipy percentileofscore 的加权版本
【发布时间】:2018-06-23 10:50:46
【问题描述】:

我想将权重传递给scipy.stats.percentileofscore。例如:

from scipy import stats
a = [1, 2, 3, 4]
val = 3
stats.percentileofscore(a, val)

返回 75,因为 a 中 75% 的值位于或低于 val 3。

我想添加权重,例如:

weights = [2, 2, 3, 3]
weightedpercentileofscore(a, val, weights)

应该返回 70,因为 (2 + 2 + 3) / (2 + 2 + 3 + 3) = 7 / 10 的权重落在或低于 3。

这也适用于小数权重和大权重,因此仅扩展数组并不理想。

Weighted percentile using numpy 是相关的,但计算的是百分位数(例如,要求第 10 个百分位数)而不是某个值的特定百分位数。

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    这应该可以完成工作。

    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.
    

    在实践中,您要做的是查看分数的总体权重小于或等于您的阈值分数 - 除以权重的总和并以百分比表示。

    将每个值对应的加权百分位数作为数组获取:

    [weighted_percentile_of_score(a, weights, val) for val in a]
    # [20.0, 40.0, 70.0, 100.0]
    

    【讨论】:

      猜你喜欢
      • 2020-01-06
      • 1970-01-01
      • 2022-01-19
      • 2020-07-07
      相关资源
      最近更新 更多