我想从 Python 中的多个大向量的集合中计算百分位数。有没有更有效的方法,而不是尝试连接向量,然后通过numpy.percentile将生成的巨大向量放入?
我的想法是,首先,计算不同值的频率(例如使用scipy.stats.itemfreq),其次,将不同向量的项目频率组合起来,最后,根据计数计算百分位数。
不幸的是,我无法找到用于组合频率表的函数(它不是很简单,因为不同的表可能涵盖不同的项目),或者用于从项目频率表计算百分位数。我需要实现这些,还是可以使用现有的 Python 函数?这些功能是什么?
小智 4
根据 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2213 次 |
| 最近记录: |