¿Cómo calculo percentiles con python/numpy?

Resuelto Uri asked hace 14 años • 12 respuestas

numpy¿Existe una forma conveniente de calcular percentiles para una secuencia o matriz unidimensional ?

Estoy buscando algo similar a la función percentil de Excel.

Uri avatar Mar 04 '10 03:03 Uri
Aceptado

NumPy tiene np.percentile().

import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50)  # return 50th percentile, i.e. median.
>>> print(p)
3.0

SciPy tiene scipy.stats.scoreatpercentile(), además de muchas otras ventajas estadísticas .

Jon W avatar Mar 03 '2010 20:03 Jon W

Por cierto, existe una implementación pura de Python de la función percentil , en caso de que uno no quiera depender de scipy. La función se copia a continuación:

## {{{ http://code.activestate.com/recipes/511478/ (r1)
import math
import functools

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

# median is 50th percentile.
median = functools.partial(percentile, percent=0.5)
## end of http://code.activestate.com/recipes/511478/ }}}
Boris Gorelik avatar May 02 '2010 11:05 Boris Gorelik

A partir de Python 3.8, la biblioteca estándar viene con la quantilesfunción como parte del statisticsmódulo:

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

quantilesdevuelve para una distribución dada distuna lista de n - 1puntos de corte que separan los nintervalos cuantiles (división disten nintervalos continuos con igual probabilidad):

stats.quantiles(dist, *, n=4, método='exclusivo')

donde n, en nuestro caso ( percentiles) es 100.

Xavier Guihot avatar Apr 23 '2019 22:04 Xavier Guihot
import numpy as np
a = [154, 400, 1124, 82, 94, 108]
print np.percentile(a,95) # gives the 95th percentile
richie avatar Jun 12 '2013 07:06 richie