Sub topic 7
Choosing your own percentiles
This chapter assumes you can run Python, have pandas imported as pd, and know how describe behaves by default: it summarizes the numeric columns and skips missing values. Here you will change which quantiles describe reports, learn the rules it enforces, and use the extra rows to judge spread and outliers.
What the default percentiles show
By default, describe reports three percentiles: 25%, 50%, and 75%. A percentile is the value below which a given share of the data falls. The 25% row is the first quartile, 50% is the median, and 75% is the third quartile.
These three rows describe the middle of the data well. They say little about the tails, where outliers and data-entry errors tend to sit. The percentiles argument lets you ask for rows such as 5% and 95%, or 1% and 99%.
Here is the DataFrame used throughout this chapter.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli"],
"age": [34, 28, np.nan, 45, 39],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo"],
"salary": [52000, 48000, 61000, 75000, 58000],
})
print(df["age"].describe(percentiles=[0.1, 0.9]))The percentiles argument takes a list of fractions between 0 and 1. For the age column, the output contains these values:
| Row | Value |
|---|---|
| count | 4.0 |
| mean | 36.5 |
| std | 7.234178 |
| min | 28.0 |
| 10% | 29.8 |
| 50% | 36.5 |
| 90% | 43.2 |
| max | 45.0 |
The default 25% and 75% rows are gone, replaced by 10% and 90%. The 50% row remains even though you did not ask for it.
Rules `describe` applies to your list
describe checks and rearranges the list you pass in. Knowing these rules explains most of the surprises you will see.
- The median is always included. If you leave 0.5 out,
describeadds it.percentiles=[]still gives you a 50% row. - Values are fractions, not percents. Pass
0.9, not90. Anything outside the range 0 to 1 raises aValueError. - Duplicates are rejected. Passing
[0.5, 0.5]raises aValueError. - Order does not matter. The rows are sorted, and they always appear between
minandmax. - Missing values are ignored. The percentiles come from the non-null values only, the same values counted in the
countrow.
You can see rules 2 and 3 fail in a short script.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5])
for bad in ([25, 75], [0.5, 0.5]):
try:
s.describe(percentiles=bad)
except ValueError as err:
print(bad, "->", type(err).__name__)
print(s.describe(percentiles=[0.9, 0.1]))Both bad lists raise ValueError. The last call succeeds even though 0.9 comes before 0.1, and the output lists 10% before 50% before 90%.
How the labels are built
Each percentile becomes a row label, made by multiplying the fraction by 100 and adding a % sign. The label uses as many decimal places as it needs to stay distinct from the others.
import pandas as pd
s = pd.Series(range(1, 1001))
result = s.describe(percentiles=[0.001, 0.025, 0.999])
print(list(result.index))The printed list is:
['count', 'mean', 'std', 'min', '0.1%', '2.5%', '50%', '99.9%', 'max']These labels are strings, so you select a row with .loc and the exact label text.
summary = df["salary"].describe(percentiles=[0.1, 0.9])
print(summary.loc["90%"])
print(summary["10%"])For the salary column, this prints 69400.0 and then 49600.0. If you are not sure how a fraction will be labelled, print summary.index first. Do not build the label from a computed float. For example, f"{0.1 * 100}%" can produce something like 10.000000000000002% in some cases, which will not match.
Where the numbers come from
describe computes percentiles with linear interpolation. If the requested position falls between two sorted values, the result is a weighted blend of them.
Take the four non-null ages, sorted: 28, 34, 39, 45. With n values, the position for a fraction p is p * (n - 1), counted from zero. For p = 0.9 and n = 4, the position is 2.7. That lies between 39 (position 2) and 45 (position 3). The result is 39 + 0.7 * (45 - 39) = 43.2, which matches the table above.
So a percentile in the output often does not appear anywhere in your data. With small samples this is easy to misread. The 10% row of 29.8 is not an age anyone has.
If you need a value that actually exists in the data, use quantile with a different interpolation setting.
print(df["age"].quantile([0.1, 0.9]))
print(df["age"].quantile([0.1, 0.9], interpolation="nearest"))The first call returns 29.8 and 43.2. The second returns 28.0 and 45.0, because "nearest" picks the closest real observation. describe does not expose this setting, so quantile is the right tool when you need it.
Using tail percentiles to find outliers
The default quartiles are resistant to extreme values, which is why they are useful, but it also means they hide the tails. Percentiles such as 5% and 95% show where the bulk of the data ends. Comparing them with min and max tells you whether the extremes are far from the rest.
Consider 99 ordinary values and one extreme one.
import pandas as pd
values = list(range(1, 100)) + [5000]
s = pd.Series(values)
print(s.describe(percentiles=[0.05, 0.95]))Selected rows from the output:
| Row | Value |
|---|---|
| count | 100.0 |
| mean | 99.5 |
| min | 1.0 |
| 5% | 5.95 |
| 50% | 50.5 |
| 95% | 95.05 |
| max | 5000.0 |
Three comparisons stand out:
- The mean (99.5) is almost double the median (50.5). A mean far above the median suggests a long right tail.
- The 95% row is 95.05, close to the ordinary values, while
maxis 5000. - The gap between 95% and
maxis the signal. In clean data the top of the range continues smoothly from the 95% row. Here it jumps by a factor of about 50.
A high percentile can still be pulled by an outlier. The 99% row for this series is 148.01, not 99. That happens because 99% falls between the 99th value (99) and the 100th value (5000), and interpolation blends them. With few observations, a very high percentile is mostly set by the single largest values.
Percentiles with `include` and other columns
Percentiles apply to numeric columns (and to datetime columns). When you combine percentiles with include="all", text columns still cannot have percentiles, so those rows are filled with NaN.
print(df.describe(include="all", percentiles=[0.1, 0.9]))In the result, the city column has NaN in the 10% and 90% rows, and the age and salary columns have numbers. The count, unique, top, and freq rows are filled in only for the columns where they apply. This sparse layout is normal and is not an error.
If you want a clean numeric-only table with custom percentiles, select the numeric columns explicitly.
numeric = df.describe(include="number", percentiles=[0.05, 0.5, 0.95])
print(numeric)This avoids the NaN rows and keeps the output easy to compare across columns. Percentiles passed to Series.describe on a text column are accepted and ignored, because that summary reports count, unique, top, and freq only.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError` about the interval | You passed `90` or `25` instead of `0.9` or `0.25` | Divide by 100 |
| `ValueError` about duplicates | The same fraction appears twice, for example `[0.5, 0.5]` | Remove the repeat |
| No 50% row requested, but it appears | The median is always added | Drop the row afterwards with `.drop("50%")` |
| `KeyError` when selecting `"90%"` | The label differs, such as `"90.0%"` or you asked for 0.899 | Print `result.index` and copy the label |
| Percentile value not in your data | Linear interpolation blends neighbours | Use `quantile(..., interpolation="nearest")` |
| `NaN` in percentile rows for a text column | `include="all"` mixes text and numeric columns | Use `include="number"` |
Removing the median row is a rare need, but it takes one call.
trimmed = df["salary"].describe(percentiles=[0.1, 0.9]).drop("50%")
print(trimmed)A reusable helper
When you inspect many tables, it helps to wrap your preferred tail percentiles in a small function so the choice is consistent.
import pandas as pd
TAILS = [0.01, 0.05, 0.95, 0.99]
def tail_summary(frame: pd.DataFrame) -> pd.DataFrame:
"""Numeric summary with the median plus 1%, 5%, 95%, and 99% rows."""
return frame.describe(include="number", percentiles=TAILS)
demo = pd.DataFrame({"x": [1, 2, 3, 4, 100], "y": [10, 11, 12, 13, 14]})
print(tail_summary(demo))The function always returns the same row set, so you can compare tables from different datasets or from before and after a cleaning step.
Summary of the key points
percentilestakes fractions from 0 to 1 and replaces the default 25%, 50%, 75% rows, except that the median is always kept.- Duplicates and values outside 0 to 1 raise
ValueError. Order does not matter. - Labels are strings such as
"10%"and"99.9%". Checkresult.indexbefore selecting by label. - Values come from linear interpolation over the non-null values, so they may not exist in your data.
- Compare tail percentiles with
min,max, and the mean to see outliers and skew. - With
include="all", text columns getNaNin percentile rows.
Exercise
A Series has the values 10, 20, 30, 40, 50. Without running code, what are the 10% and 90% rows from describe(percentiles=[0.1, 0.9])? Then write the call that would return the same two numbers using quantile.
Show answer
With n = 5, the position for 0.1 is 0.1 4 = 0.4, so the value is 10 + 0.4 (20 - 10) = 14. The position for 0.9 is 0.9 4 = 3.6, so the value is 40 + 0.6 (50 - 40) = 46. The matching call is s.quantile([0.1, 0.9]), which returns 14.0 and 46.0.
Exercise
You call df.describe(percentiles=[5, 95]) and get an error. Name the error type, explain the cause, and give the corrected call. After the fix, which row labels appear between min and max?
Show answer
The error is a ValueError, because percentiles must be fractions between 0 and 1 and 5 and 95 are outside that range. The corrected call is df.describe(percentiles=[0.05, 0.95]). The labels between min and max are 5%, 50%, and 95%, since the median is added automatically.
Exercise
A numeric column has a mean of 820, a median of 410, a 95% row of 560, and a max of 90000. What do these numbers suggest, and what would you check next?
Show answer
The mean is about twice the median, and the max is far above the 95% row. Together they suggest a long right tail caused by a few extreme values, which could be genuine large cases or errors such as extra zeros or placeholder codes. Next, sort the column in descending order, look at the largest rows, and decide whether they are valid before you clean or analyse the data.