算法-分位数
分位数
分位数(Quantile),亦称分位点,是指将一个随机变量的概率分布范围分为几个等份的数值点,常用的有中位数(即二分位数)、四分位数、百分位数等。
1 使用 numpy
code
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# 中位数
print(np.median(a))
# 25%分位数
print(np.percentile(a, 25))
# 75%分位数
print(np.percentile(a, 75))
result
5.5
3.25
7.75
2 使用 math
math
包及其基本函数-ceil
可用于计算不同的百分比。
完整的示例代码如下。
import math
arry=[1,2,3,4,5,6,7,8,9,10]
def calculate_percentile(arry, percentile):
size = len(arry)
index = math.ceil((size * percentile) / 100)
if index != 0:
index = index - 1
return sorted(arry)[int(index)]
percentile_25 = calculate_percentile(arry, 25)
percentile_50 = calculate_percentile(arry, 50)
percentile_75 = calculate_percentile(arry, 75)
# 2
print("The 25th percentile is:",percentile_25)
# 5
print("The 50th percentile is:",percentile_50)
# 7
print("The 75th percentile is:",percentile_75)
Last updated