DS Percentiles
A percentile tells you the value below which a given percentage of observations fall. The 90th percentile of Riverside Bikes' daily rides is about 494: on 90 % of days the service rented 494 bikes or fewer — and only on the busiest 10 % of days more than that.
Percentiles are how operations teams plan capacity: you don't stock enough bikes for the average day, you stock enough for, say, 90 % of days.
Computing a percentile
For a quick intuition, take ten values. Sort them; the 50th percentile (the median) sits in the middle, and the others are found by interpolating between neighbours:
import numpy as np
rides = np.array([414, 298, 439, 405, 254, 523, 497, 428, 209, 368])
print("sorted:", np.sort(rides))
for p in [10, 25, 50, 75, 90]:
print(f"{p}th percentile: {np.percentile(rides, p):.2f}")sorted: [209 254 298 368 405 414 428 439 497 523]
10th percentile: 249.50
25th percentile: 315.50
50th percentile: 409.50
75th percentile: 436.25
90th percentile: 499.60
np.percentile(data, p) uses linear interpolation by default: the 25th percentile of ten values lies a quarter of the way between positions, so it is usually not one of the observed values. Other methods exist (method="lower", "nearest", …) and give slightly different answers on small samples; on large data they hardly differ.
Quartiles and the IQR
Three percentiles are so common that they have their own name, quartiles:
| Name | Percentile | Meaning |
|---|---|---|
| Q1 (lower quartile) | 25th | a quarter of days are at or below this |
| Q2 (median) | 50th | half of days are at or below this |
| Q3 (upper quartile) | 75th | three quarters of days are at or below this |
The interquartile range IQR = Q3 − Q1 measures the spread of the middle half of the data. Unlike the range, it ignores the extremes.
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
q = bikes["rides"].quantile([0.25, 0.5, 0.75, 0.9])
print(q)
iqr = q[0.75] - q[0.25]
print("IQR:", iqr)
print("Range:", bikes["rides"].max() - bikes["rides"].min())0.25 263.25
0.50 364.50
0.75 444.50
0.90 494.20
Name: rides, dtype: float64
IQR: 181.25
Range: 448
pandas calls them quantiles and takes fractions (0.9) rather than percentages (90), but the idea is identical. Half of all days had between about 263 and 445 rides.
Using percentiles for planning
The manager wants enough bikes on the street for 90 % of days, separately for weekdays and weekends. groupby plus quantile gives both at once:
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
p90 = bikes.groupby("weekend")["rides"].quantile(0.9)
print(p90)
print()
# what share of days would a 500-ride capacity cover?
print("Share of days with rides <= 500:", (bikes["rides"] <= 500).mean().round(3))weekend
0 459.0
1 546.5
Name: rides, dtype: float64
Share of days with rides <= 500: 0.933
The last line inverts the question: instead of "which value covers 90 % of days?", it asks "which percentage of days does a given value cover?" — the percentile rank of 500.
Visualising percentiles: the box plot
A box plot draws the quartiles directly: the box spans Q1 to Q3, the line inside is the median, and the whiskers reach to the furthest points within 1.5 × IQR of the box. Points beyond the whiskers are drawn individually as potential outliers.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
bikes.boxplot(column="rides", by="weekend")
plt.suptitle("")
plt.title("Daily rides: weekdays (0) vs weekends (1)")
plt.ylabel("Rides")
plt.show()
print("Box plot of rides for", bikes["weekend"].nunique(), "groups")Box plot of rides for 2 groups
The weekend box sits clearly higher: weekend days are busier across the board, not only on average.
Test yourself
The 75th percentile of daily rides is 445. What does that mean?
- 75 days had 445 rides
- On 75 % of days there were 445 rides or fewer
- The average is 445
- 445 is 75 % of the maximum
How is the interquartile range (IQR) calculated?
- max − min
- Q3 − Q1
- mean − median
- Q2 / 2
In pandas, which call returns the 90th percentile of column rides?
df["rides"].percentile(90)df["rides"].quantile(0.9)df["rides"].quantile(90)np.quantile(df, 90)