11.1. Percentiles#

Hide code cell source

path_data = '../../data/'

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
%matplotlib inline

delivery = pd.read_csv(path_data + 'delivery_days.csv')
days = delivery['days_to_deliver'].values

An online store has to tell customers when their order will arrive. Quote too short a time and many orders are late; quote too long a time and shoppers go to a competitor. A good promise comes from the data: look at how long recent orders actually took and pick a delivery time that most of them met.

A percentile is the tool for this. It locates one value within ordered numerical data, such as “the delivery time that 90% of orders met.” This section explains how percentiles are computed, applies them to 400 recent orders to choose a delivery promise, and then uses the first and third quartiles to describe the middle of the data. Along the way, you will see why you have to be careful about what a percentile of one sample does and does not tell you.

11.1.1. From Testing to Estimating#

In the chapters on hypothesis testing and two-sample comparisons, every question had a yes-or-no flavor. Is the promotion pattern consistent with a fair process? Is the traffic split really 50-50? Did the new page beat the old one, or could chance alone explain the difference? Each time you built a model, simulated its predictions, and asked whether the data were consistent with it.

Many business questions are not yes-or-no. A store does not ask “Is the typical delivery time 5 days?” It asks “How long does delivery take?” A manager does not ask “Is the average order exactly $50?” but “What is the average order?” The answer is a number, and the task is to find a good value for it and to say how far off it might be. This is called estimation.

The store’s 400 recent orders are a sample: the observed subset used for estimation. All of the store’s orders, including those it has not shipped yet, constitute the population: the full group or process of interest. There are two different jobs hiding in this work, and it helps to keep them apart.

  • Describing a sample. The store has the delivery times of 400 recent orders. Computing their median or 90th percentile is just arithmetic on the data at hand. There is nothing uncertain about it.

  • Estimating a population value. The store really cares about all orders, including the ones it has not shipped yet. The 400 orders are one sample from that larger process. A number computed from a sample is the best available estimate of the corresponding number in the population, and a different sample would yield a slightly different estimate.

Recall from Sampling Variability that a parameter is a number that describes a population, and a statistic is a number computed from a sample. The parameter usually cannot be computed because the whole population is not available, so a statistic is used as an estimate of it. The 90th percentile of the 400 sampled orders is a statistic. The 90th percentile of delivery time for all orders, past and future, is the parameter it estimates.

Estimation vs. Hypothesis Testing

Estimation and hypothesis testing are the two primary pillars of statistical inference, used to draw conclusions about a population using sample data. They differ fundamentally in their core question and output.

Feature

Estimation

Hypothesis Testing

Core Question

“What is the value (or range of values) of this population parameter?”

“Is there enough evidence to reject a specific claim or null hypothesis about the population?”

What It Does

Uses sample data to approximate an unknown population quantity (like a mean, proportion, or regression coefficient).

Evaluates whether observed sample data conform to a pre-specified baseline assumption (\(H_0\)) versus an alternative hypothesis (\(H_1\)).

Key Forms

Point Estimation: Single best-guess number (e.g., \(\bar{x} = 50\)).

Interval Estimation: Range of plausible values with uncertainty, like a confidence or credible interval (e.g., 95% CI: \([45, 55]\)).

Uses test statistics, significance levels (\(\alpha\)), p-values (frequentist), or Bayes factors (Bayesian) to quantify how much the data disagree with the null hypothesis.

Primary Output

A number or an interval (e.g., effect size, mean, CI).

A p-value, test statistic, or Bayes factor.

Need for Null Hypothesis

Not required.

Central to the procedure.

Focus / Goal

Magnitude: quantifying how much or where a parameter lies, and how uncertain it is.

Decision or evidence evaluation: assessing whether a specific claim holds, e.g., whether an effect is statistically distinguishable from zero or a baseline.

Data Science Context

Measuring customer lifetime value, A/B lift magnitude, or model weights (\(\beta\)).

Deciding if a new feature beats the old one (A/B testing).

This section builds the descriptive tools: percentiles and quartiles. The next two sections (The Bootstrap and Confidence Intervals) address the second job, which is deciding how much to trust such a statistic.

11.1.1.1. Practice#

### Exercise: Statistic or Parameter
# all_orders holds the delivery days of every order a small shop shipped last month.
# The shop's analyst looked only at sample_orders, five of those orders.
#   1. Compute the median of the sample. This is a statistic.
#   2. Compute the median of all orders. This is the parameter it estimates.
#   3. Print which of the two an analyst usually cannot compute: statistic or parameter.
# Print exactly:
# Statistic (sample median): 5.0
# Parameter (median of all orders): 4.0
# Usually unknown: parameter
import numpy as np
all_orders = np.array([2, 3, 3, 4, 4, 4, 5, 6, 7, 9])
sample_orders = np.array([3, 5, 6, 4, 9])
### Your code starts here.

print("Statistic (sample median):", np.median(sample_orders))
print("Parameter (median of all orders):", np.median(all_orders))
print("Usually unknown: parameter")

### Your code ends here.
Statistic (sample median): 5.0
Parameter (median of all orders): 4.0
Usually unknown: parameter

Hide code cell source

### Solution
import numpy as np
all_orders = np.array([2, 3, 3, 4, 4, 4, 5, 6, 7, 9])
sample_orders = np.array([3, 5, 6, 4, 9])
print('Statistic (sample median):', np.median(sample_orders))
print('Parameter (median of all orders):', np.median(all_orders))
print('Usually unknown: parameter')
# The parameter usually cannot be computed: in real work only the sample is
# available, so the sample median is used as an estimate of it.
Statistic (sample median): 5.0
Parameter (median of all orders): 4.0
Usually unknown: parameter

11.1.2. A Small Example#

Before using 400 orders, look at five. Suppose a store records the delivery times, in days, of five orders: 9, 4, 12, 3, and 6.

A percentile calculation starts by sorting the values. Under the nearest convention used in this chapter, the 80th percentile is the observed value found at the zero-based position nearest to (n - 1) * 80 / 100, where n is the number of values. Zero-based means that the first sorted value is at position 0. Here that position is (5 - 1) * 80 / 100 = 3.2.

small = np.array([9, 4, 12, 3, 6])
sorted_small = np.sort(small)
position = (len(small) - 1) * 80 / 100

print('Sorted values:', sorted_small)
print('Position:', position)
Sorted values: [ 3  4  6  9 12]
Position: 3.2

The nearest whole position to 3.2 is 3, and position 3 of [3, 4, 6, 9, 12] holds the value 9. So the 80th percentile of these five delivery times is 9 days. Four of the five orders, or 80%, took 9 days or less.

For the 70th percentile the position is (5 - 1) * 70 / 100 = 2.8. Its nearest whole number is also 3, so the answer is again 9. With a small dataset, different percentile requests can land on the same observed value.

The code below finds each position with int(np.rint(...)). np.rint rounds to the nearest whole number, and int turns the result into a whole number you can use as an index.

print('80th percentile:', sorted_small[int(np.rint(position))])
print('70th percentile:', sorted_small[int(np.rint((len(small) - 1) * 70 / 100))])
80th percentile: 9
70th percentile: 9

A percentile under this convention is always one of the values in the data. It is neither the average of two neighbors nor a value invented between them.

11.1.3. The np.percentile Function#

You do not need to sort and count positions by hand. The pattern is np.percentile(values, percentage, method='nearest'). The general syntax is:

numpy.percentile(a, q, axis=None, out=None, overwrite_input=False, 
                 method='linear', keepdims=False, *, weights=None)

Parameter

Meaning

a

Input array (or array-like).

q

Percentile(s) to compute, from 0 to 100; scalar or sequence.

axis

Axis or axes to compute along; None (default) flattens the array.

out

Optional existing array to store the result in.

overwrite_input

If True, allows a to be modified in place to save memory.

method

Interpolation method when the percentile falls between two data points; default 'linear'.

keepdims

If True, keeps the reduced axes as size-1 dimensions.

weights

Optional weights for each value (NumPy 2.0+; only works with method='inverted_cdf').

The data come first, followed by a percentage from 0 to 100, inclusive. You can pass a list of percentages to get several percentiles at once.

np.percentile(values, percentage, method='nearest')


np.percentile(values, [25, 50, 75], method='nearest')

These are syntax patterns: replace values with your array or Series and percentage with the requested percentage.

NumPy’s default method is linear, which interpolates between observations and returns a value that was never observed. You have already seen this. In Descriptive Distributions you called np.percentile without a method, so NumPy used linear, and the first quartile of total_bill came out as $13.3475, an amount no bill could have. This chapter always asks for method='nearest' so that the convention is visible and the answer is an actual delivery time. The hypothesis-testing sections used the default linear method when they took the 95th percentile of thousands of simulated statistics. With that many values, the two methods yield nearly the same result, so those results stand; with a small dataset, they can differ, which is why this chapter names its method. See the NumPy percentile documentation .

Apply the function to the five-order example. The answers should match the hand calculation above.

print('80th percentile:', np.percentile(small, 80, method='nearest'))
print('70th percentile:', np.percentile(small, 70, method='nearest'))
print('All three at once:', np.percentile(small, [25, 50, 75], method='nearest'))
80th percentile: 9
70th percentile: 9
All three at once: [4 6 9]

The function sorts the data itself, so you can pass values in any order.

11.1.3.1. Percentiles and the Median#

In general, the pth percentile is a value that about p% of the observations are at or below. Under the nearest convention it is the sorted value at the whole position nearest to (n - 1) * p / 100, so the 0th percentile is the minimum and the 100th is the maximum.

The median needs one extra warning. For an ordinary median, use np.median(values) or series.median(): with an even number of observations it averages the two middle values. A nearest-method 50th percentile instead picks one observed value, so for an even number of values the two can differ. For [1, 2, 3, 4], the nearest-method 50th percentile selects position 1.5, which NumPy rounds to 2, giving 3. The ordinary median averages 2 and 3, giving 2.5. In this book, “the median” means the ordinary median.

Two habits are enough for this chapter: ask for method='nearest' and say so when you report a percentile, and use np.median for the median.

More on percentile conventions (optional)

Halfway ties. When the position is exactly halfway between two whole numbers, NumPy rounds to the even one: 1.5 becomes 2, and 2.5 also becomes 2. np.rint follows the same rule, so the by-hand check always agrees with np.percentile.

Other conventions. A different, valid convention uses the one-based rank ceil(n * p / 100) for positive p. This is the inverse empirical distribution rule, available as method='inverted_cdf'. NumPy offers several more methods. On small datasets they can give different answers for the same data, which is why a reported percentile should name its method.

11.1.3.2. Practice#

### Exercise: Compare Two Conventions
# For these four values, compute the nearest-method 50th percentile and
# the ordinary median. Print both, then print whether they are equal.

# Print exactly:
# Nearest 50th percentile: 3
# Ordinary median: 2.5
# Same value: False
import numpy as np
values = np.array([1, 2, 3, 4])
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
import numpy as np
values = np.array([1, 2, 3, 4])
nearest = np.percentile(values, 50, method='nearest')
median = np.median(values)
print('Nearest 50th percentile:', nearest)
print('Ordinary median:', median)
print('Same value:', bool(nearest == median))
# Nearest selects one observed value; the median averages the middle two.
Nearest 50th percentile: 3
Ordinary median: 2.5
Same value: False

11.1.4. Delivery-Time Promises#

Now the store’s question. The file delivery_days.csv lists 400 recent orders and the number of days each took to arrive. The store is hypothetical, and the delivery times are simulated for this book. The data are right-skewed: most orders arrive within a few days, and a few are much slower. Start by looking at the shape.

print('Orders:', len(days))
print('Mean:', round(days.mean(), 2), 'days')
print('Median:', np.median(days), 'days')
print('Fastest:', days.min(), 'day; slowest:', days.max(), 'days')

day_values, counts = np.unique(days, return_counts=True)

fig, ax = plt.subplots(figsize=(7, 3.8))
ax.bar(day_values, counts, color='#4c72b0', edgecolor='white')

ax.set_xlabel('Days to deliver')
ax.set_ylabel('Number of orders')
ax.set_title('Most orders arrive within a week; a few take much longer')
plt.show()
Orders: 400
Mean: 4.53 days
Median: 4.0 days
Fastest: 1 day; slowest: 11 days
../../_images/4af48ed84995125449f723462f8545dc961232858448f21772bfce5a91813f8a.png

The median is 4 days, but a promise of “4 days” would be broken for 44.5% of the orders, nearly half. A store wants a promise that most orders keep. Suppose management decides on this target: promise a time that 90% of orders met. That is the 90th percentile.

promise = np.percentile(days, 90, method='nearest')

print('90th percentile:', promise, 'days')
90th percentile: 7 days

So the store could advertise “delivery within 7 days.” Check what that promise would have meant for these 400 orders.

within = (days <= promise).sum()
late = (days > promise).sum()
print('Orders delivered within', promise, 'days:', within, 'of', len(days))
print('Share within the promise:', within / len(days))
print('Orders that would have been late:', late)

day_values, counts = np.unique(days, return_counts=True)
colors = np.where(day_values <= promise, '#4c72b0', '#c44e52')

fig, ax = plt.subplots(figsize=(7, 3.8))
ax.bar(day_values, counts, color=colors, edgecolor='white')
ax.axvline(promise + 0.5, color='black', linestyle='--', lw=1.5, 
           label=f'Promise: {promise} days')

ax.set_xlabel('Days to deliver')
ax.set_ylabel('Number of orders')
ax.set_title(f'{within} orders met the promise; {late} would have been late')
ax.legend()
plt.show()
Orders delivered within 7 days: 367 of 400
Share within the promise: 0.9175
Orders that would have been late: 33
../../_images/8821ec93c88f2e4ec061e14f8e871cfb84de1210bc1507a21958620c87fbed26.png

Of the 400 orders, 367 arrived in 7 days or less, which is 91.75%. That is a little above 90% because delivery times are whole days and many orders tie at exactly 7 days. A percentile of discrete data usually cannot hit the stated percentage exactly. The 33 orders slower than 7 days are the ones the store would have to apologize for: the red bars to the right of the dashed line.

11.1.4.1. Checking the Index by Hand#

To see that np.percentile is not doing anything mysterious, repeat its work. First sort the 400 delivery times and compute the zero-based position (n - 1) * 0.90.

sorted_days = np.sort(days)
n = len(sorted_days)
j = (n - 1) * 0.90
print('n:', n)
print('Position:', round(j, 1))
n: 400
Position: 359.1

The position is 359.1. Round it to 359, which is the 360th element of the sorted list because counting starts at 0. Select that value.

index = int(np.rint(j))
print('Index:', index)
print('Value at that index:', sorted_days[index])
print('np.percentile says:', np.percentile(days, 90, method='nearest'))
Index: 359
Value at that index: 7
np.percentile says: 7

The two agree: 7 days. In the sorted list, positions 336 through 366 (31 orders) all hold 7, so a small difference in rounding would not have changed the answer here.

11.1.4.2. A Higher Promise#

What if the store wants a stronger promise, one that 95% of orders meet? Use the 95th percentile.

promise95 = np.percentile(days, 95, method='nearest')
within95 = (days <= promise95).sum()

print('95th percentile:', promise95, 'days')
print('Orders within', promise95, 'days:', within95, 'of', len(days))
print('Share within the promise:', within95 / len(days))
print('Orders that would have been late:', (days > promise95).sum())
95th percentile: 8 days
Orders within 8 days: 389 of 400
Share within the promise: 0.9725
Orders that would have been late: 11

The 95th percentile is 8 days. Promising 8 days instead of 7 would have kept the promise for 389 of the 400 orders, or 97.25%, and cut the number of late orders from 33 to 11. The price is a longer advertised delivery time, which may cost sales. Choosing between 7 and 8 days is a business decision about the cost of broken promises versus the cost of looking slow. The percentile’s job is to show the trade-off in numbers.

One caution carries into the rest of the chapter. These percentiles describe the 400 orders in the file. They say “91.75% of these orders took 7 days or less.” They do not guarantee that 90% of next month’s orders will. A different sample of 400 orders would likely give a slightly different 90th percentile, and the next two sections show how to measure that uncertainty.

11.1.4.3. Practice#

### Exercise: Promise a Delivery Time
# A store's express lane shipped 20 orders. Their delivery times in days
# are in express_days.
#   1. Compute the nearest-method 80th percentile with np.percentile.
#   2. Check it by sorting the values and selecting the index nearest
#      (n - 1) * 0.80. Use int(np.rint(...)).
#   3. Count how many orders arrived within that many days.
#   4. Print the three results.

# Print exactly:
# np.percentile: 5
# By hand: 5
# Orders within the promise: 16 of 20
import numpy as np
express_days = np.array([2, 3, 3, 4, 2, 5, 3, 6, 4, 3, 7, 2, 4, 3, 9, 3, 5, 4, 3, 12])
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
import numpy as np
express_days = np.array([2, 3, 3, 4, 2, 5, 3, 6, 4, 3, 7, 2, 4, 3, 9, 3, 5, 4, 3, 12])
ex_promise = np.percentile(express_days, 80, method='nearest')
sorted_express = np.sort(express_days)
ex_index = int(np.rint((len(sorted_express) - 1) * 0.80))
by_hand = sorted_express[ex_index]
ex_within = int((express_days <= ex_promise).sum())
print('np.percentile:', ex_promise)
print('By hand:', by_hand)
print('Orders within the promise:', ex_within, 'of', len(express_days))
# Orders tie at the promised value, so the share can differ from 80%.
np.percentile: 5
By hand: 5
Orders within the promise: 16 of 20

11.1.5. Quartiles#

Percentiles at 25, 50, and 75 split ordered data into four parts. The first quartile is the 25th percentile and the third quartile is the 75th percentile. The 50th percentile sits between them. As always, state the convention used when you report quartiles; here they are calculated with method='nearest', and the ordinary median is calculated separately.

q1, q3 = np.percentile(days, [25, 75], method='nearest')

print('First quartile:', q1)
print('Median (ordinary):', np.median(days))
print('Nearest 50th percentile:', np.percentile(days, 50, method='nearest'))
print('Third quartile:', q3)
First quartile: 3
Median (ordinary): 4.0
Nearest 50th percentile: 4
Third quartile: 6

Because 400 is an even number of orders, the ordinary median averages the 200th and 201st sorted values. Here both are 4 days, so the nearest-method 50th percentile gives the same answer. That agreement is not guaranteed in general, as the four-value exercise showed.

The interval from the first quartile to the third describes the middle half of the orders: the typical delivery times once the fastest and slowest quarters are set aside. Its width, third quartile minus first quartile, is the interquartile range (IQR). Unlike the range from fastest to slowest, the IQR is not stretched by a few extreme orders.

iqr = q3 - q1
print('Interquartile range:', iqr, 'days')

in_middle = ((days >= q1) & (days <= q3)).sum()

print('Orders from', q1, 'to', q3, 'days:', in_middle, 'of', len(days))
print('Share:', in_middle / len(days))
print('Fastest to slowest range:', days.max() - days.min(), 'days')
Interquartile range: 3 days
Orders from 3 to 6 days: 282 of 400
Share: 0.705
Fastest to slowest range: 10 days

The first quartile is 3 days, and the third is 6 days, so the middle half of orders arrive between 3 and 6 days, with an IQR of 3 days. The fastest-to-slowest range is 10 days, more than three times as wide, because of a handful of slow orders.

Notice that 282 orders, or 70.5%, fall between 3 and 6 days. That is more than half because delivery times are whole days and many orders tie at the quartile values. With ties and the finite-sample percentile conventions, the interval from the first to third quartile need not hold exactly 50% of the observations.

Two percentiles that bracket a middle share of the values are also how this chapter will express uncertainty. In The Bootstrap, the middle 95% of many estimates runs from their 2.5th to their 97.5th percentile, and that interval becomes the estimate.

11.1.5.1. Practice#

### Exercise: The Middle Half of Express Orders
# Use the 20 express-lane delivery times (in days) from the earlier exercise.
#   1. Compute the first and third quartiles with
#      np.percentile(..., [25, 75], method='nearest').
#   2. Compute the interquartile range and the fastest-to-slowest range.
#   3. Print the four results.

# Print exactly:
# First quartile: 3
# Third quartile: 5
# Interquartile range: 2
# Fastest to slowest range: 10
import numpy as np
express_days = np.array([2, 3, 3, 4, 2, 5, 3, 6, 4, 3, 7, 2, 4, 3, 9, 3, 5, 4, 3, 12])
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
import numpy as np
express_days = np.array([2, 3, 3, 4, 2, 5, 3, 6, 4, 3, 7, 2, 4, 3, 9, 3, 5, 4, 3, 12])
ex_q1, ex_q3 = np.percentile(express_days, [25, 75], method='nearest')
print('First quartile:', ex_q1)
print('Third quartile:', ex_q3)
print('Interquartile range:', ex_q3 - ex_q1)
print('Fastest to slowest range:', express_days.max() - express_days.min())
# One 12-day order stretches the full range; the IQR ignores it.
First quartile: 3
Third quartile: 5
Interquartile range: 2
Fastest to slowest range: 10

11.1.6. Section Practice#

Use this exercise to check the main workflow from this section.

### Exercise: Practice Percentiles
# A call center recorded 12 hold times in minutes. The manager wants a target
# that 90% of calls meet and a summary of a typical wait.
#   1. Compute the nearest-method 90th percentile and count the calls at or under it.
#   2. Compute the first and third quartiles (method='nearest') and the IQR.
#   3. Print the four results.

# Print exactly:
# 90th percentile: 12
# Calls within the target: 11 of 12
# Q1 to Q3: 4 to 8 minutes
# Interquartile range: 4
import numpy as np
hold_times = np.array([3, 7, 2, 12, 5, 4, 9, 6, 15, 3, 8, 5])
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
import numpy as np
hold_times = np.array([3, 7, 2, 12, 5, 4, 9, 6, 15, 3, 8, 5])
target = np.percentile(hold_times, 90, method='nearest')
ex_within = int((hold_times <= target).sum())
ex_q1, ex_q3 = np.percentile(hold_times, [25, 75], method='nearest')
print('90th percentile:', target)
print('Calls within the target:', ex_within, 'of', len(hold_times))
print('Q1 to Q3:', ex_q1, 'to', ex_q3, 'minutes')
print('Interquartile range:', ex_q3 - ex_q1)
# Eleven of these 12 calls met a 12-minute target, and the quartiles of the
# wait are 4 and 8 minutes. These describe this sample: they do not
# guarantee that 90% of future calls will meet the target.
90th percentile: 12
Calls within the target: 11 of 12
Q1 to Q3: 4 to 8 minutes
Interquartile range: 4