Search code examples
pythonnumpystatisticsquantilepercentile

How do I calculate percentiles with python/numpy?


Is there a convenient way to calculate percentiles for a sequence or single-dimensional numpy array?

I am looking for something similar to Excel's percentile function.


Solution

  • NumPy has 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 has scipy.stats.scoreatpercentile(), in addition to many other statistical goodies.