Sub topic 6
Summarizing numeric columns with describe
This chapter assumes you can read basic Python and have pandas imported as pd. It also assumes you know a DataFrame is a table of rows and labelled columns. You should have already previewed data with head and tail and checked dtypes and non-null counts with info. Here you will learn what describe computes, how to read each row of its output, and where it can mislead you.
What describe does
DataFrame.describe() returns a new DataFrame of summary statistics. It is a quick check on the center, spread, and range of each numeric column. The method computes these values from the non-missing entries only.
We will use the same small table throughout. It has one missing age.
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.describe().round(2))The output looks like this:
age salary
count 4.00 5.00
mean 36.50 58800.00
std 7.23 10377.86
min 28.00 48000.00
25% 32.50 52000.00
50% 36.50 58000.00
75% 40.50 61000.00
max 45.00 75000.00By default only numeric columns appear. name and city are missing from the result because they hold text. The result is itself a DataFrame. Its index holds the statistic names and its columns are the original numeric columns. You can therefore select from it like any other table, for example df.describe().loc["mean"].
Reading each row
Each row answers a different question about the column.
| Row | Meaning | What to check |
|---|---|---|
| count | Number of non-missing values | Compare with the number of rows. A lower count means missing data. |
| mean | Arithmetic average | Compare with the median. A large gap suggests skew or outliers. |
| std | Sample standard deviation (divides by n - 1) | A value near zero means the column barely varies. |
| min | Smallest value | Look for impossible values such as negative ages. |
| 25% | First quartile | A quarter of the values fall at or below this. |
| 50% | Median | The middle value. It is not pulled by extremes. |
| 75% | Third quartile | Three quarters of the values fall at or below this. |
| max | Largest value | Look for implausible peaks. |
count and missing data
For age, count is 4 while the table has 5 rows. The missing value was skipped. This is the same information info reports as a non-null count, shown in a different place. The mean of 36.5 is the sum 146 divided by 4, not by 5.
std uses n - 1
The std row is the sample standard deviation. For age the deviations from the mean are -2.5, -8.5, 8.5, and 2.5. Their squares sum to 157, and 157 / 3 = 52.33. The square root is 7.23. The divisor is n - 1 (the count minus one), not n. If you need the population version, call df["age"].std(ddof=0) separately.
How quartiles are computed
Quartiles are found by linear interpolation between neighbouring sorted values. The sorted ages are 28, 34, 39, 45. The 25% position is 0.25 × (4 − 1) = 0.75, which is three quarters of the way from 28 to 34. That gives 28 + 0.75 × 6 = 32.5. The result need not equal any value in the data. With few rows, interpolated quartiles can look odd, so treat them as rough on tiny tables.
Choosing your own percentiles
The percentiles argument takes a list of fractions between 0 and 1. It replaces the default quartiles.
print(df.describe(percentiles=[0.1, 0.9]).round(2)) age salary
count 4.00 5.00
mean 36.50 58800.00
std 7.23 10377.86
min 28.00 48000.00
10% 29.80 49600.00
50% 36.50 58000.00
90% 43.20 69400.00
max 45.00 75000.00Two behaviours are worth knowing:
- The median (50%) is always included, even if you leave it out of the list.
- The labels come from your fractions. A value of 0.995 becomes
99.5%.
Wide percentile bands such as 1% and 99% are useful for outlier hunting. They show how far the extremes sit from the bulk of the data.
print(df.describe(percentiles=[0.01, 0.99]).round(2))Values outside the 0 to 1 range raise a ValueError, so write 0.9 and not 90.
Choosing columns with include and exclude
By default describe summarizes numeric columns only. If the table has no numeric columns at all, it summarizes the object columns instead. The include and exclude arguments override this behaviour.
print(df.describe(include="all"))With include="all", every column appears. The result takes the union of the statistics. Rows that do not apply to a column are filled with NaN. For example age gets NaN under unique, top, and freq. city gets NaN under mean and std. This produces a wide, sparse table, so use it for a quick look rather than for further computation.
You can also be specific:
# Only numeric columns, stated explicitly
print(df.describe(include="number").round(2))
# Everything except numeric columns
print(df.describe(exclude="number"))
# Only float columns
print(df.describe(include=[float]).round(2))Some details to remember:
includeandexcludeaccept dtype names, dtype classes, or lists of them. Strings such as"number"and"category"work too.include="all"cannot be combined withexclude.- Selecting by the string
"object"can miss text columns that use a newer dedicated string dtype, depending on your pandas version. Checkdf.dtypesand useexclude="number"ifinclude="object"returns an empty or unexpected result. - If your selection matches no columns, pandas raises a
ValueError.
Summarizing text and categorical columns
For non-numeric columns, describe reports a different set of statistics:
| Row | Meaning |
|---|---|
| count | Number of non-missing values |
| unique | Number of distinct values |
| top | The most frequent value |
| freq | How often the top value occurs |
print(df["city"].describe())
print(df["age"].describe())
print(df.isna().sum())Calling describe on a single column uses Series.describe. It returns a Series, not a DataFrame. For city, count is 5 and unique is 3. In this table Lima and Oslo both occur twice, so top is one of them and which one is not a meaningful result. When counts tie, top is an arbitrary pick among the tied values. If you need the full picture, use df["city"].value_counts().
For age, the Series version gives the same numbers as the numeric DataFrame table, in one column. The last line, df.isna().sum(), counts missing values per column. It should agree with the gap between the row count and each count in the summary. Here age has one missing value.
Datetime columns are handled like categorical ones in older pandas and with numeric-like statistics in current versions. Check the output on your own version before relying on it.
Spotting problems in the numeric summary
The summary is most useful when you compare rows against each other. Here is a version of the table with a suspicious salary and an impossible age:
messy = pd.DataFrame({
"age": [34, 28, -1, 45, 39, 41],
"salary": [52000, 48000, 61000, 75000, 58000, 5800000],
})
print(messy.describe().round(1)) age salary
count 6.0 6.0
mean 31.0 1015666.7
std 17.0 2335419.3
min -1.0 48000.0
25% 29.5 53500.0
50% 36.5 59500.0
75% 40.5 71500.0
max 45.0 5800000.0Work through the signals:
- A negative minimum.
minfor age is -1, which is not a valid age. It is probably a placeholder for "unknown". - Mean far above the median. Salary has a mean of about 1,015,667 and a median of 59,500. One extra zero in the last row drags the mean up. When mean and median differ this much, suspect an outlier or a skewed distribution.
- Standard deviation larger than the mean. For salary, std is about 2.3 million against a mean of 1.0 million. This is another sign of a heavy tail.
- Max far beyond the 75% mark. The 75% value is 71,500 and the max is 5,800,000. The spread between these two is large compared with the spread between min and 25%.
- Counts below the row count. Any
countsmaller than the length of the table means missing values.
None of these signals proves an error. They tell you where to look. A real salary of 5.8 million could be correct. Follow up by selecting those rows, for example messy[messy["salary"] > 1_000_000].
Limits and gotchas
- Boolean columns. Booleans are treated as categorical, not numeric. They give count, unique, top, and freq.
- Numbers stored as text. If a numeric column was read as strings, it is excluded from the default summary. Missing numeric columns in the output usually point to a wrong dtype, so check
df.dtypesordf.info(). - Display precision. The default display shows six decimals, and large tables use scientific notation. Chain
.round(2)or setpd.set_option("display.float_format", "{:.2f}".format)if output is hard to read. - Integer columns. Even integer columns produce float results, because the mean and quartiles can be fractional.
- Not a distribution plot. Eight numbers cannot show bimodal data or clusters. Use a histogram when the summary raises doubts.
Quick reference
df.describe() # numeric columns only
df.describe(percentiles=[0.05, 0.95]) # custom quantiles
df.describe(include="all") # numeric and non-numeric together
df.describe(exclude="number") # non-numeric columns only
df["salary"].describe() # one column, returned as a Series
df.describe().T # one row per columnExercises
Exercise
A column called price shows count 480, mean 120.5, 50% 35.0, and max 9,800.0 in a table with 500 rows. Name two problems or warning signs and one follow-up step for each.
Show answer
First, count is 480 against 500 rows, so 20 values are missing. Check them with df["price"].isna().sum() or by selecting the rows where price is null. Second, the mean (120.5) is far above the median (35.0) and the max is huge. This points to outliers or a skewed distribution. Look at the largest rows with df.nlargest(10, "price") and check whether they are errors or valid values.
Exercise
Write code that summarizes only the numeric columns of df, reports the 5th and 95th percentiles in addition to the median, and rounds the result to one decimal place.
Show answer
print(df.describe(percentiles=[0.05, 0.95]).round(1)). The median is added automatically, and the default numeric-only behaviour already skips name and city.