I am trying to wrap my head around the implementation of the quantile function for finite samples and, specifically, in numpy
(main reason to do this: I am working on conformal predictions). It is likely I am missing something clear and welcome anyone who can point out my clear mistake!
Assume we observe values $\mathcal{X} = \{x_1, x_2 \ldots x_n\}$ and we want to calculate the $p \in [0, 1]$ quantile from the observed sample. So, we denote the quantile function over this finite sample as $Q(q, \mathcal{X})$.
If I check the Wikipedia page of quantile (https://en.wikipedia.org/wiki/Quantile), we have that the quantile are defined as follows:
$Q(p, \mathcal{X}) := x: P(X<x) \leq p \text{ and } P(X\leq x) \geq p$
I am not 100% sure how to interpret "$P(X<x)$" here. I assume this is a reference to the e.c.d.f. (https://en.wikipedia.org/wiki/Empirical_distribution_function) of $\mathcal{X}$. That is, "$P(X<x)$" is operationalized as the proportion of points in the sample less than $x$. Therefore, we get the following equivalent definition:
$Q(p, \mathcal{X}) = \text{sup}\{x \in \mathbb{R} : \text{ecdf}_\mathcal{X}(x) < p \}$.
So far so good, I believe. Assume $\mathcal{X} = \{2,3,4,10 \}$. Now let's check numpy
implementation:
import numpy as np
v = np.array([2,3,4,10])
q_third = np.quantile(v, 1/3) # 3
assert q_third == 3 # This is true! quantile is exactly 3
I am at loss here. numpy
tells me that $Q(\frac{1}{3}, \{2,3,4,10 \}) = 3$. Based on the definition above, I expected that $Q(\frac{1}{4}, \{2,3,4,10 \}) = 3$ . In fact, the definition above is ambiguous w.r.t. to $ Q(\frac{1}{3}, \{2,3,4,10 \})$ as far as I understand.
Under to linear interpolation (the default method in numpy
) we can assume that $Q(\frac{1}{4}, \{2,3,4,10 \}) \neq Q(\frac{1}{3}, \{2,3,4,10 \})$. So, either me or numpy
are wrong. I tend to think numpy
must be correct here, but I cannot spot my error. If anyone can explain to me, I would be grateful.
I acknowledge that there is a similar question (Definition of quantile), but the answer to said question simply reports the same Wikipedia definition above and refers to R (irrelevant in this context). An explanation of the logic numpy
applies in my example (hopefully in the same notation I use) will be accepted as an answer.
numpy.quantile
isnone
, so you only have the elements of the set to choose from. (numpy.org/doc/stable/reference/generated/numpy.quantile.html) $\endgroup$