在python中计算百分位数

时间:2019-04-23 18:38:27

标签: python arrays numpy

我有一个大型阵列 [1,4,5,9,1,4,6,....]

我想计算总数低于每个百分位数的元素。 例如:

4 numbers in 10percentile
7 numbers in 20 percentile
10 numbers in 30 percentile and so on till 100. ```

Is there a simple way to do this

1 个答案:

答案 0 :(得分:2)

您绝对可以使用np.percentile来做到这一点,但也需要编写一些自己的代码。在这里,我正在用字典来做。最后一个for循环不是很必要,但我这样做只是出于演示目的。

arr=np.array([1,2,3,4,5,6,1,5,3,6,2,6,3,5,2,6,8,6,78,97,77,45])

percentile=np.percentile(arr,np.arange(10,110,10))

dic={}
for i,j in zip(percentile,np.arange(10,110,10)):
    dic[j]=np.sum(arr<=i)

for key,value in dic.items():
    print(str(value)+' numbers in '+str(key)+' percentile')

结果:

5 numbers in 10 percentile
5 numbers in 20 percentile
8 numbers in 30 percentile
9 numbers in 40 percentile
12 numbers in 50 percentile
17 numbers in 60 percentile
17 numbers in 70 percentile
17 numbers in 80 percentile
19 numbers in 90 percentile
22 numbers in 100 percentile