Thursday, October 6, 2022

[FIXED] How to get the quartiles of a list of integers

Issue

I have a function which I want to find Q1, Q2, and Q3 of a list of ordered integers.

intList = [5, 10, 14, 15, 26, 30, 31, 33, 34, 47, 64]

def quartiles(numbers):
    Q1, Q2, Q3 = np.quantile(numbers, [0.25, 0.5, 0.75], axis=0)
    return {
        'Q1': Q1,
        'Q2': Q2,
        'Q3': Q3
    }

The function is returning:

{'Q1': 14.5, 'Q2': 30.0, 'Q3': 33.5}

But the actual Q1, Q2, Q3 are 14, 30, and 34.


Solution

By default numpy.quantile is performing an interpolation. I believe you rather want the nearest point.

You can use the method='nearest' parameter (NB. this requires numpy ≥ 1.22.0, for previous versions use interpolation='nearest' instead):

intList = [5, 10, 14, 15, 26, 30, 31, 33, 34, 47, 64,]

def quartiles(numbers):
    Q1, Q2, Q3 = np.quantile(numbers, [0.25, 0.5, 0.75], axis=0, method='nearest')
    return {
        'Q1': Q1,
        'Q2': Q2,
        'Q3': Q3
    }

Output: {'Q1': 14, 'Q2': 30, 'Q3': 34}



Answered By - mozway
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.