如何计算 python 中的分布百分比

How to count percentile of distribution in python

是否有任何 python/numpy 函数可以计算给定概率分布的第 n 个百分位数?

# Like This
distr = [.2, .6, .2]
do_some_magic(distr, 50)  # 1
distr = [.1, .1, .6, .2]
do_some_magic(distr, 50)  # 2

是的,您可以使用 scipy 的 percentileofscore

from scipy.stats import percentileofscore

distr = [.2, .6, .2]

print(percentileofscore(distr,50)/100)
1.0

尝试以下选项

NumPy 方法:

import numpy as np


distr = np.array([.2, .6, .2])
percentile = np.percentile(distr, 50)

print(percentile)

Python 方法:

import math


def percentile(data, perc: int):
    size = len(data)
    return sorted(data)[int(math.ceil((size * perc) / 100)) - 1]

distr = [.2, .6, .2]

print(percentile(distr, 50))

输出:0.2