【发布时间】:2018-06-24 07:23:47
【问题描述】:
我想计算一个列表(或 numpy 数组)中每个值的百分位数,由另一个列表中的权重加权。例如,给定一些 f 我想要:
x = [1, 2, 3, 4]
weights = [2, 2, 3, 3]
f(x, weights)
产生[20, 40, 70, 100]。
我可以使用
计算单个项目的未加权百分位数from scipy import stats
stats.percentileofscore(x, 3)
# 75.0
每 Map each list value to its corresponding percentile 我也可以为每个使用计算这个
[stats.percentileofscore(x, a, 'rank') for a in x]
# [25.0, 50.0, 75.0, 100.0]
根据Weighted version of scipy percentileofscore,我可以使用以下方法计算单个项目的加权百分位数:
def weighted_percentile_of_score(x, weights, score, kind='weak'):
npx = np.array(x)
npw = np.array(weights)
if kind == 'rank': # Equivalent to 'weak' since we have weights.
kind = 'weak'
if kind in ['strict', 'mean']:
indx = npx < score
strict = 100 * sum(npw[indx]) / sum(weights)
if kind == 'strict':
return strict
if kind in ['weak', 'mean']:
indx = npx <= score
weak = 100 * sum(npw[indx]) / sum(weights)
if kind == 'weak':
return weak
if kind == 'mean':
return (strict + weak) / 2
称为:
weighted_percentile_of_score(x, weights, 3)) # 70.0 as desired.
我如何(有效地)为列表中的每个项目执行此操作?
【问题讨论】: