有没有办法从排序列表中获取累计和的百分比指数?

时间:2018-02-21 03:48:47

标签: python list numpy percentage cumulative-sum

给出实数的排序列表,例如

x = range(20)

任务是找到列表累积和的X%的第一个索引,例如

def compute_cumpercent(lint, percent):
    break_point = sum(lint) * percent
    mass = 0
    for i, c in enumerate(lint):
        if mass > break_point:
            return i
        mass += c

要查找输入列表中小于和接近累计和的25%的数字索引,

>>> compute_cumpercent(x, 0.25)
11

首先,是否存在此类函数的数学/名称?

除了使用上述简单循环执行此操作外,是否可以使用numpy或某些bisect或其他方式执行相同操作?

假设输入列表始终排序。

3 个答案:

答案 0 :(得分:1)

这样的事可能吗?

import numpy as np

x = range(20)
percent = 0.25

cumsum = np.cumsum(x)
break_point = cumsum[-1] * percent
np.argmax(cumsum >= break_point) + 1 # 11

答案 1 :(得分:0)

import numpy as np
x = np.arange(20)
Percent = 25

CumSumArray = np.cumsum(x)
ValueToFind = CumSumArray[-1] * Percent / 100
Idx = np.argmax(CumSumArray > ValueToFind)[0] - 1

答案 2 :(得分:0)

this hint之后,可以使用searchsorted查找元素的索引,该索引接近(低于)百分位数/分位数。

请参见以下示例:

import numpy as np

def find_index_left(xs, v):
   return np.searchsorted(xs, v, side='left') - 1

def find_index_quantile(xs, q):
    v = np.quantile(xs, q)
    return find_index_left(xs, v)

xs = [5, 10, 11, 15, 20]
assert np.quantile(xs, 0.9) == 18.0
assert find_index_left(xs, 18) == 3 # zero-based index for forth element
assert find_index_quantile(xs, 0.9) == 3

注意xs必须排序。