Search code examples
pythonnumpyquantile

Numpy function to get the quantile that corresponds to a given value


I see a lot of questions like this one for R, but I couldn't find one specifically for Python, preferably using numpy.

Let's say I have an array of observations stored in x. I can get the value that accumulates q * 100 per cent of the population.

# Import numpy
import numpy as np

# Get 75th percentile
np.quantile(a=x, q=0.75)

However, I was wondering if there's a function that does the inverse. That is, a numpy function that takes a value as an input and returns q.

To further expand on this, scipy distribution objects have a ppf method that allows me to do this. I'm looking for something similar in numpy. Does it exist?


Solution

  • Not a ready-made function but a compact and reasonably fast snippet:

    (a<value).mean()
    

    You can (at least on my machine) squeeze out a few percent better performance by using np.count_nonzero

    np.count_nonzero(a<value) / a.size
    

    but tbh I wouldn't even bother.