PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 6, 2022

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

 October 06, 2022     math, numpy, python, statistics     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing