如何计算数组中间隔的百分比

时间:2013-08-23 09:56:47

标签: python numpy pandas scipy

>>> import numpy as np
>>> standart_perc = [50, 75, 80, 85, 90, 95, 98, 99, 100]
>>> a = np.arange(110)
>>> np.percentile(a, standart_perc)
[54.5, 81.75, 87.200000000000003, 92.649999999999991, 98.100000000000009, 103.55, 106.81999999999999, 107.91, 109.0]

如何计算54.5和81.75,81.75和87.200000000000003之间的值百分比。?

3 个答案:

答案 0 :(得分:3)

a[(a > 54.5) & (a <  81.75)].size / float(a.size)

<强>更新

In [6]: a = np.random.randint(1, 110, 1000000)
In [7]: %%timeit
        percentileofscore(a, 81.75) - percentileofscore(a, 54.5)
1 loops, best of 3: 373 ms per loop
In [8]: %%timeit
        a[(a > 54.5) & (a <  81.75)].size / float(a.size)
10 loops, best of 3: 20.5 ms per loop

似乎percentileofscore慢得多。

答案 1 :(得分:0)

我认为您正在寻找scipy.stats.percentileofscore

percentileofscore(a, 54.5) == 50.
percentileofscore(a, 81.75) == 75.

减去这些将给你25(分数在54.5和81.75之间的百分比)。

这意味着你可以使用map反转np.percentile,然后应用shift和subtract来获得你所追求的“如果数组在间隔中的百分比”。

答案 2 :(得分:0)

Python 中使用 循环时这样做:

>>> a
[54.5, 81.75, 87.2, 92.64999999999999, 98.10000000000001, 103.55, 106.82, 107.91, 109.0]
>>> i = 0
>>> while i < len(a)-1:
...     print a[i]/a[i+1]*100
...     i = i+1
... 
66.6666666667
93.75
94.1176470588
94.4444444444
94.7368421053
96.9387755102
98.9898989899
99.0