是否有一种方便的方法来计算一个序列或一维numpy数组的百分位数?
我正在寻找类似Excel的百分位数函数。
我在NumPy的统计参考中找不到这个。我所能找到的是中位数(第50百分位),但没有更具体的东西。
是否有一种方便的方法来计算一个序列或一维numpy数组的百分位数?
我正在寻找类似Excel的百分位数函数。
我在NumPy的统计参考中找不到这个。我所能找到的是中位数(第50百分位),但没有更具体的东西。
当前回答
检查scipy。统计模块:
scipy.stats.scoreatpercentile
其他回答
我引导数据,然后绘制出10个样本的置信区间。置信区间表示概率在5%到95%之间的范围。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import json
import dc_stat_think as dcst
data = [154, 400, 1124, 82, 94, 108]
#print (np.percentile(data,[0.5,95])) # gives the 95th percentile
bs_data = dcst.draw_bs_reps(data, np.mean, size=6*10)
#print(np.reshape(bs_data,(24,6)))
x= np.linspace(1,6,6)
print(x)
for (item1,item2,item3,item4,item5,item6) in bs_data.reshape((10,6)):
line_data=[item1,item2,item3,item4,item5,item6]
ci=np.percentile(line_data,[.025,.975])
mean_avg=np.mean(line_data)
fig, ax = plt.subplots()
ax.plot(x,line_data)
ax.fill_between(x, (line_data-ci[0]), (line_data+ci[1]), color='b', alpha=.1)
ax.axhline(mean_avg,color='red')
plt.show()
下面是如何在没有numpy的情况下,仅使用python来计算百分比。
import math
def percentile(data, perc: int):
size = len(data)
return sorted(data)[int(math.ceil((size * perc) / 100)) - 1]
percentile([10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0], 90)
# 9.0
percentile([142, 232, 290, 120, 274, 123, 146, 113, 272, 119, 124, 277, 207], 50)
# 146
import numpy as np
a = [154, 400, 1124, 82, 94, 108]
print np.percentile(a,95) # gives the 95th percentile
要计算一个系列的百分位数,运行:
from scipy.stats import rankdata
import numpy as np
def calc_percentile(a, method='min'):
if isinstance(a, list):
a = np.asarray(a)
return rankdata(a, method=method) / float(len(a))
例如:
a = range(20)
print {val: round(percentile, 3) for val, percentile in zip(a, calc_percentile(a))}
>>> {0: 0.05, 1: 0.1, 2: 0.15, 3: 0.2, 4: 0.25, 5: 0.3, 6: 0.35, 7: 0.4, 8: 0.45, 9: 0.5, 10: 0.55, 11: 0.6, 12: 0.65, 13: 0.7, 14: 0.75, 15: 0.8, 16: 0.85, 17: 0.9, 18: 0.95, 19: 1.0}
从Python 3.8开始,标准库附带了quantiles函数,作为统计模块的一部分:
from statistics import quantiles
quantiles([1, 2, 3, 4, 5], n=100)
# [0.06, 0.12, 0.18, 0.24, 0.3, 0.36, 0.42, 0.48, 0.54, 0.6, 0.66, 0.72, 0.78, 0.84, 0.9, 0.96, 1.02, 1.08, 1.14, 1.2, 1.26, 1.32, 1.38, 1.44, 1.5, 1.56, 1.62, 1.68, 1.74, 1.8, 1.86, 1.92, 1.98, 2.04, 2.1, 2.16, 2.22, 2.28, 2.34, 2.4, 2.46, 2.52, 2.58, 2.64, 2.7, 2.76, 2.82, 2.88, 2.94, 3.0, 3.06, 3.12, 3.18, 3.24, 3.3, 3.36, 3.42, 3.48, 3.54, 3.6, 3.66, 3.72, 3.78, 3.84, 3.9, 3.96, 4.02, 4.08, 4.14, 4.2, 4.26, 4.32, 4.38, 4.44, 4.5, 4.56, 4.62, 4.68, 4.74, 4.8, 4.86, 4.92, 4.98, 5.04, 5.1, 5.16, 5.22, 5.28, 5.34, 5.4, 5.46, 5.52, 5.58, 5.64, 5.7, 5.76, 5.82, 5.88, 5.94]
quantiles([1, 2, 3, 4, 5], n=100)[49] # 50th percentile (e.g median)
# 3.0
Quantiles为给定的分布区域返回n - 1个切割点的列表,分隔n个分位数区间(以等概率将dist划分为n个连续区间):
统计数据。分位数(dist, *, n=4, method='exclusive')
在我们的例子中,n(百分位数)是100。