Menu
CoddyTech

Percentiles and Quartiles

Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 2 of 64.

A percentile cuts sorted data: the 25th lies a quarter of the way up, the 50th is the median. Nine escape room times:

Nine escape room times as dots on a line, from 38 to 95 seconds. Lines mark Q1 at 45, Q2 at 52 and Q3 at 61, and a shaded box from Q1 to Q3 is labelled middle half, IQR of 16

The cuts into quarters are the quartiles Q1, Q2 and Q3. np.percentile(a, q) takes q from 0 to 100, or a list:

times = np.array([52, 38, 61, 45, 70, 41, 95, 58, 49])
print(np.percentile(times, [25, 50, 75]))

This prints:

[45. 52. 61.]

The middle half spans Q1 to Q3; its width is the interquartile range, Q3 - Q1: 16 seconds.

Make the slowest time 950: the IQR stays 16. Trust it when a feature has extremes.

challenge icon

Challenge

Easy

A customer asks how their water use compares with their street's 20 homes. use holds the homes' liters, and the program reads the customer's. Print:

  1. The quartiles of use: Q1, the median, Q3.
  2. The IQR.
  3. The customer's quarter: 1 below Q1, 2 below the median, 3 below Q3, otherwise 4.

For a street of 12 homes and the input 172:

Quartiles: 157.5, 170.5, 183.5 liters
IQR: 26.0 liters
This home is in quarter 3

Try it yourself

import numpy as np

# Liters of water each home used yesterday
use = np.array([312, 285, 410, 198, 356, 274, 520, 301, 289, 345,
                262, 398, 230, 610, 327, 295, 368, 251, 334, 280])
liters = int(input())

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Statistics for ML

Practice on your own: Online Python compiler