A student gets "99 percentile" in an entrance exam. That doesn't mean 99 marks or 99% correct. It means they scored higher than about 99% of the candidates who sat the exam. A percentile describes a value by its position in the data: what share of values lie below it.
Positions turn out to be very useful. The median is the 50th percentile. The 25th and 75th percentiles, called the quartiles, mark where the middle half of the data sits, and the distance between them, the interquartile range or IQR, measures spread without being thrown off by extreme values. That makes the IQR the go-to measure of spread for skewed data such as salaries, delivery times and house prices, and the basis of the standard rule for spotting outliers.
What you need first: mean, median and mode, range, variance and standard deviation and frequency tables and histograms.
Key terms
- Percentile: the *p*th percentile is the value below which about p% of the data falls.
- Quartiles: the 25th, 50th and 75th percentiles, called Q1, Q2 (the median) and Q3. They cut the sorted data into four equal parts.
- Interquartile range (IQR): Q3 − Q1, the width of the middle 50% of the data.
- Five-number summary: minimum, Q1, median, Q3 and maximum.
- Box plot: a chart of the five-number summary, with outliers shown as separate dots.
- Outlier: a value unusually far from the rest. A common rule flags values more than 1.5 × IQR beyond the quartiles.
Percentiles: position, not marks
A food delivery app records 20 delivery times, in minutes:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
times = pd.Series([18, 22, 25, 19, 31, 27, 24, 21, 35, 26, 23, 29, 20, 24, 58, 22, 28, 25, 30, 26])
print(times.sort_values().to_list())
print("median:", times.median())
print("90th percentile:", round(times.quantile(0.9), 1))
[18, 19, 20, 21, 22, 22, 23, 24, 24, 25, 25, 26, 26, 27, 28, 29, 30, 31, 35, 58]
median: 25.0
90th percentile: 31.4
quantile(0.9) finds the 90th percentile; pandas uses fractions, so 0.9 means 90%. Read it as: 90% of deliveries arrived within this many minutes. Companies love this number. "Our average delivery takes 26 minutes" hides the customers who waited much longer. "90% of orders arrive within 31.4 minutes" is a promise about almost everyone.
The exam percentile works the same way, from the other direction. If a score is at the 99th percentile, 99% of scores are below it. With 10 lakh candidates, about 10,000 scored higher.
Quartiles: the data in four parts
The three quartiles split the sorted data into four groups with the same number of values in each:
q1, q2, q3 = times.quantile([0.25, 0.5, 0.75])
print(q1, q2, q3)
print("IQR:", q3 - q1)
22.0 25.0 28.25
IQR: 6.25
- Q1 (25th percentile): a quarter of deliveries were faster than this.
- Q2 is the median: half were faster.
- Q3 (75th percentile): three quarters were faster.
The IQR, Q3 − Q1, is the width of the middle half of the deliveries. Half of all deliveries took between Q1 and Q3 minutes.
Why the IQR resists outliers
One delivery took 58 minutes: the rider got lost. Compare how the standard deviation and the IQR react to it. Predict which one changes more if you remove that delivery:
without = times[times != 58]
print("SD: ", round(times.std(), 2), "->", round(without.std(), 2))
print("IQR:", times.quantile(0.75) - times.quantile(0.25), "->", without.quantile(0.75) - without.quantile(0.25))
SD: 8.51 -> 4.36
IQR: 6.25 -> 5.5
The standard deviation shrinks a lot, because the single 58 contributed a huge squared deviation. The IQR hardly moves: it only depends on the values around the quarter marks, and the lost rider isn't anywhere near them. The IQR is to the SD what the median is to the mean: a robust version that extreme values can't drag around.
The five-number summary and the box plot
Minimum, Q1, median, Q3 and maximum together are the five-number summary. A box plot draws it:
- the box runs from Q1 to Q3, so its length is the IQR;
- a line inside the box marks the median;
- the whiskers reach out to the furthest values that aren't outliers;
- outliers are drawn as separate dots.
Box plots are best for comparing groups side by side. Here are real penguin body masses by species. Before you run it, use what you know from earlier lessons to guess which box will sit highest:
Download the data: penguins.csv (15 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("penguins.csv").
import seaborn as sns
penguins = sns.load_dataset("penguins").dropna(subset=["body_mass_g"])
species = ["Adelie", "Chinstrap", "Gentoo"]
groups = [penguins.loc[penguins["species"] == s, "body_mass_g"] for s in species]
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.boxplot(groups, tick_labels=species, patch_artist=True,
boxprops={"facecolor": "#fbe9dc", "edgecolor": "#c2410c"},
medianprops={"color": "#c2410c", "linewidth": 2.5})
ax.set_ylabel("Body mass (g)")
ax.set_title("Gentoo penguins are heavier; the other two overlap")
plt.show()
ax.boxplot takes one list of values per box; tick_labels names them, and the props settings colour the boxes and medians. In one glance you can see three facts that took several tables in earlier lessons: Gentoos are heavier, Adelies and Chinstraps overlap almost completely, and each species has a similar spread.
The 1.5 × IQR rule for outliers
How far out does a value need to be to count as an outlier? The usual rule, and the one box plots use, draws two fences:
- lower fence = Q1 − 1.5 × IQR
- upper fence = Q3 + 1.5 × IQR
Anything beyond the fences is flagged. For the deliveries:
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"fences: {lower} to {upper}")
print(times[(times < lower) | (times > upper)].to_list())
fences: 12.625 to 37.625
[58]
The lost rider's 58 minutes is flagged. The | means "or": a value is an outlier if it's below the lower fence or above the upper one.
Treat the rule as a flag, not a verdict. An outlier can be a mistake (a typo, a sensor fault), and then it should be fixed or removed. Or it can be real and important: the lost rider really happened, and a delivery company that deleted such orders would never fix the problem. Always look at flagged values before deciding what to do with them.
Outliers in real, skewed data
In a long-tailed column, the 1.5 × IQR rule flags many values. Titanic ticket fares are a good example: most passengers paid little, and a few paid a fortune.
Download the data: titanic.csv (58 KB), or from the original source, the seaborn-data repository on GitHub. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("titanic.csv").
fare = sns.load_dataset("titanic")["fare"]
f_q1, f_q3 = fare.quantile([0.25, 0.75])
f_upper = f_q3 + 1.5 * (f_q3 - f_q1)
print(f"Q1 {f_q1:.1f}, Q3 {f_q3:.1f}, upper fence {f_upper:.1f}")
print(f"{(fare > f_upper).sum()} of {len(fare)} fares are above the fence")
Q1 7.9, Q3 31.0, upper fence 65.6
116 of 891 fares are above the fence
Over a hundred fares are "outliers", but they aren't mistakes: they're first-class tickets. When a rule flags this many values, it's telling you the data has a long tail, not that it's full of errors. Removing them would delete most of first class. You'll see how to handle long tails in skewness and kurtosis.
Why pandas and NumPy can give different percentiles
With only 4 values, what's the 25th percentile of 10, 20, 30, 40? There's no value exactly a quarter of the way in, so tools must interpolate: pick a point between two values. Different methods pick different points:
small = np.array([10, 20, 30, 40])
print(np.percentile(small, 25))
print(np.percentile(small, 25, method="lower"))
print(np.percentile(small, 25, method="nearest"))
17.5
10
20
NumPy's and pandas' default ("linear") places the 25th percentile a quarter of the way along the sorted positions and interpolates between neighbours. Other methods round to an actual data value. Spreadsheets and other software sometimes use yet another rule. With large datasets the differences are tiny; with small ones they can matter, so don't be alarmed if a textbook's quartiles differ slightly from Python's.
Where machine learning uses percentiles
- Robust scaling: scikit-learn's
RobustScalersubtracts the median and divides by the IQR, so outliers don't distort the scaling the way they distortStandardScaler's mean and SD. - Clipping extreme values: capping a feature at its 1st and 99th percentiles limits the damage a few extreme values can do to a linear model.
- Equal-sized bins:
pd.qcut(x, 4)splits a column into quartile groups, each with the same number of rows. - Measuring systems: a prediction service is judged by its 95th or 99th percentile response time, because the average hides the slow requests users complain about.
Common mistakes
- Confusing percentile with percentage. A 70 percentile score isn't 70% marks; it's a position in the group.
- Deleting every flagged outlier. Check whether it's an error or a real, important case first.
- Using the 1.5 × IQR rule on long-tailed data and panicking. Many flags mean a long tail; consider a log scale or a robust model instead.
- Expecting quartiles to match across tools. Small datasets give slightly different answers under different interpolation methods.
Practice
- In a class of 200, a student is at the 80th percentile. About how many students scored below them?
Show the answer
About 80% of 200, so about 160 students.
- Predict, then check: what is the 50th percentile of
times, and why?
Show the answer
It's the median, because the median is the value with half the data below it.
print(times.quantile(0.5), times.median())
25.0 25.0
- A dataset has Q1 = 40 and Q3 = 60. Which of these values are outliers by the 1.5 × IQR rule: 5, 15, 85, 95?
Show the answer
IQR = 20, so the fences are 40 − 30 = 10 and 60 + 30 = 90. Outliers are 5 and 95. 15 and 85 are inside the fences.
- Find Q1, the median and Q3 of flipper length for each species. Which species has the longest flippers, and do any two species' middle halves (Q1 to Q3) overlap?
Show the answer
print(penguins.groupby("species")["flipper_length_mm"].quantile([0.25, 0.5, 0.75]).unstack())
0.25 0.50 0.75
species
Adelie 186.0 190.0 195.0
Chinstrap 191.0 196.0 201.0
Gentoo 212.0 216.0 221.0
quantile([...]) gives three numbers per species, and unstack() lays them out as columns. Gentoo has clearly the longest flippers, and its middle half doesn't overlap the others. The Adelie and Chinstrap middle halves overlap partly, with Chinstraps a little longer. You could draw these as box plots with the same code as the body-mass chart.
- Explain in your own words why removing the 58-minute delivery changed the SD a lot but the IQR hardly at all.
Show the answer
The SD squares every deviation from the mean, so one value far away contributes a huge amount. The IQR only depends on the values at the quarter and three-quarter positions of the sorted data, and removing the slowest delivery barely shifts those positions.
Interview questions
How would you detect outliers in a feature?
Start with plots: a histogram and a box plot. Numerically, flag values beyond 1.5 × IQR from the quartiles, or with |z| > 3 for roughly normal data, or use model-based methods such as isolation forests for many features. Then investigate flagged values before removing, capping or keeping them, since outliers may be errors or important rare cases.
Why is the IQR more robust than the standard deviation?
The IQR depends only on the 25th and 75th percentiles, which move little when extreme values change. The standard deviation uses squared deviations of every value, so a single extreme value can inflate it greatly.
Key takeaways
- The *p*th percentile is the value below which about p% of the data falls: a position, not a score.
- Quartiles cut sorted data into four equal groups; the IQR, Q3 − Q1, is the width of the middle half.
- The IQR is a robust measure of spread: it barely reacts to outliers, unlike the SD.
- Box plots draw the five-number summary and are ideal for comparing groups.
- The 1.5 × IQR rule flags possible outliers; investigate them, don't delete them automatically.
Frequently asked questions
What's the difference between a percentile and a quantile?
A quantile is the general idea, given as a fraction: the 0.9 quantile. A percentile is the same thing on a 0 to 100 scale: the 90th percentile. Quartiles are the 0.25, 0.5 and 0.75 quantiles.
Why 1.5 times the IQR?
It's a convention from the statistician John Tukey. For normally distributed data, it flags only about 0.7% of values, so in well-behaved data it rarely fires. Some people use 3 × IQR to flag only extreme outliers.
What do the whiskers of a box plot show?
In Matplotlib's default, each whisker reaches the most extreme value that is still within 1.5 × IQR of the box. Values beyond that are drawn as separate points. Other tools sometimes draw whiskers to the minimum and maximum instead, so check before comparing charts.
What to learn next
- Measure lopsided data in skewness and kurtosis.
- Measure how unusual a single value is in z-scores and standardisation.
- See robust scaling next to standard scaling in feature scaling.