Linear interpolation in numpy quantile()

Question:

Consider the following code:

>>> import numpy as np
>>> l = [21,22,24,24,26,97]
>>> np.quantile(l, 0.25)
22.5

The documentation says:

linear: i + (j – i) * fraction, where fraction is the fractional part of the index surrounded by i and j.

Could anyone please explain what are i, j and fraction in this example and how we get 22.5?

Asked By: Maxim Blumental

||

Answers:

It works roughly like this:

import numpy as np


def my_quantile(array, q):
    n = len(array)
    index = (n - 1) * q
    if int(index) == index:  # has no fractional part
        return array[index]
    fraction = index - int(index)
    left = int(index)
    right = left + 1
    i, j = array[left], array[right]
    return i + (j - i) * fraction


if __name__ == '__main__':
    arr = [21, 22, 24, 24, 26, 97]
    assert my_quantile(arr, 0.33) == np.quantile(arr, 0.33)
    assert my_quantile(arr, 0.25) == np.quantile(arr, 0.25)
    assert my_quantile(arr, 0.75) == np.quantile(arr, 0.75)
Answered By: Maxim Blumental

Very nice solution, but fails. To correct it :

  • take return array[int(index)] instead of return array[index] when there is no fractional part
  • sort the array at the beginning 🙂 array = np.sort(array) at the beginning
Answered By: anonymous prof
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.