用PYTHON实现TP99等中位数统计的功能

2021-06-25  本文已影响0人  bluepang

# 中位数计算原理

1、先按升序排列 [2s, 10s, 100s, 1000s]

2、找到你需要用做统计的最后一个条目(向高取整)对应的数值,比如:TP50就是第 ceil(4*0.5)=2 个,即 10s ;TP90就是第 ceil(4*0.9)=4 个,即 1000s 。


# 方法一

def percentile(N, percent, key=lambda x:x):

    """

    Find the percentile of a list of values.

    @parameter N - is a list of values. Note N MUST BE already sorted.

    @parameter percent - a float value from 0.0 to 1.0.

    @parameter key - optional key function to compute value from each element of N.

    @return - the percentile of the values

    """

    if not N:

        return None

    k = (len(N)-1) * percent

    f = math.floor(k)

    c = math.ceil(k)

    if f == c:

        return key(N[int(k)])

    d0 = key(N[int(f)]) * (c-k)

    d1 = key(N[int(c)]) * (k-f)

    return d0+d1

# 方法二

import numpy as np

a = np.array([1,2,3,4,5])

p = np.percentile(a, 50) # 中位数

print p

上一篇下一篇

猜你喜欢

热点阅读