我想计算percentiles来自 Python 中多个大向量的集合。而不是尝试连接向量,然后将生成的巨大向量放入 numpy.percentile ,有没有更高效的方法?
我的想法是,首先,计算不同值的频率(例如使用 scipy.stats.itemfreq ),其次,将这些项目频率组合为不同的向量,最后,根据计数计算百分位数。
不幸的是,我无法找到用于组合频率表的函数(这不是很简单,因为不同的表可能涵盖不同的项目),或者用于从项目频率表计算百分位数的函数。我需要实现这些,还是可以使用现有的 Python 函数?这些功能是什么?
最佳答案
根据 Julien Palard 的建议,使用 collections.Counter
解决第一个问题(计算和组合频率表),以及我对第二个问题的实现(从频率表计算百分位数):
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)
关于python - 来自值计数的百分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070086/