价值计数的百分位数


问题内容

我想从Python中多个大型向量的集合中计算百分位数。而不是尝试连接向量,然后将所得的巨大向量放入numpy.percentile,有没有更有效的方法?

我的想法是,首先,对不同值的频率进行计数(例如,使用scipy.stats.itemfreq),其次,将这些项的频率组合成不同的向量,最后,从计数中计算百分位数。

不幸的是,我无法找到用于合并频率表的功能(这不是很简单,因为不同的表可能涵盖不同的项目),或者无法从项目频率表计算百分位数。我需要实现这些,还是可以使用现有的Python函数?这些功能是什么?


问题答案:

使用collections.Counter用于解决第一个问题(计算,结合频率表)以下朱利安Palard的建议下,我实现了第二个问题(从计算频数表百分位数):

from collections import Counter

def calc_percentiles(cnts_dict, percentiles_to_calc=range(101)):
    """Returns [(percentile, value)] with nearest rank percentiles.
    Percentile 0: <min_value>, 100: <max_value>.
    cnts_dict: { <value>: <count> }
    percentiles_to_calc: iterable for percentiles to calculate; 0 <= ~ <= 100
    """
    assert all(0 <= p <= 100 for p in percentiles_to_calc)
    percentiles = []
    num = sum(cnts_dict.values())
    cnts = sorted(cnts_dict.items())
    curr_cnts_pos = 0  # current position in cnts
    curr_pos = cnts[0][1]  # sum of freqs up to current_cnts_pos
    for p in sorted(percentiles_to_calc):
        if p < 100:
            percentile_pos = p / 100.0 * num
            while curr_pos <= percentile_pos and curr_cnts_pos < len(cnts):
                curr_cnts_pos += 1
                curr_pos += cnts[curr_cnts_pos][1]
            percentiles.append((p, cnts[curr_cnts_pos][0]))
        else:
            percentiles.append((p, cnts[-1][0]))  # we could add a small value
    return percentiles

cnts_dict = Counter()
for segment in segment_iterator:
    cnts_dict += Counter(segment)

percentiles = calc_percentiles(cnts_dict)