Sub topic 7
Summarizing numeric columns
This chapter covers how to condense a numeric column into a few numbers and how to read them. It assumes you have already loaded train.csv into a DataFrame called df and looked at df.shape, df.head(), and df.info(). It also assumes you know what missing values are (the previous chapter covered them). You need pandas installed and a notebook or script to run the code.
Why summarize before plotting
A table of 891 passengers is too large to read row by row. Summary statistics compress each column into a handful of values: how many entries it has, where its center is, how spread out it is, and where its extremes lie. They also work as a validity check. A negative age, a fare of 0, or a count far below the row count tells you something about the data before you build anything on it.
Running describe
DataFrame.describe() summarizes every numeric column by default.
import pandas as pd
df = pd.read_csv("train.csv")
pd.set_option("display.float_format", "{:.2f}".format)
print(df.describe())The first line of the setting only changes how floats print. The data itself is untouched.
The output has eight rows for each numeric column:
| Row | Meaning |
|---|---|
| count | Number of non-missing values |
| mean | Arithmetic average |
| std | Sample standard deviation (divides by n - 1) |
| min | Smallest value |
| 25% | First quartile: a quarter of values are at or below it |
| 50% | Median: half of values are at or below it |
| 75% | Third quartile |
| max | Largest value |
Pandas treats PassengerId, Survived, Pclass, SibSp, and Parch as numeric because they are stored as integers. That does not mean averaging them is meaningful. The sections below cover each case.
Reading the output column by column
Count
count excludes missing values, so it is a second way to find them. In the Titanic data, Age has a count of 714 while most other columns show 891. Those 177 missing ages are not part of any statistic computed for Age. The mean age of 29.70 describes only the passengers whose age was recorded.
Mean versus median
The mean is pulled by extreme values. The median is not. Comparing them shows whether a column is symmetric or skewed.
Agehas a mean of about 29.70 and a median of 28. They are close, so the distribution is roughly symmetric.Farehas a mean of about 32.20 and a median of about 14.45. The mean is more than double the median. A few very expensive tickets (the maximum is about 512.33) drag the mean upward.
For a skewed column like Fare, the median is a better description of a typical passenger. The mean is still useful, for example when you want the total revenue per ticket sold, but it is not "typical."
Standard deviation
The standard deviation of Fare is about 49.69, larger than its mean. For a column that cannot go below zero, a standard deviation larger than the mean is a strong sign of a long right tail. Do not read it as "most fares are within 49 of the mean." That rule of thumb only works for roughly bell-shaped data.
Min and max
Look at the extremes for plausibility. Age ranges from 0.42 to 80. A fractional age is a baby recorded in fractions of a year, which is valid. Fare has a minimum of 0. A zero fare can be a real free ticket (crew members, staff, or guests) or a placeholder for unknown. The data does not say which. Note it and move on, and do not silently delete these rows.
Quartiles and the spread of the middle
The 25% and 75% rows give the interquartile range (IQR), which is the third quartile minus the first. It describes the spread of the middle half of the data and, unlike the standard deviation, is not distorted by extreme values.
q1 = df["Fare"].quantile(0.25)
q3 = df["Fare"].quantile(0.75)
iqr = q3 - q1
print(f"Q1={q1:.2f} Q3={q3:.2f} IQR={iqr:.2f}")For Fare the IQR is roughly 23, far smaller than the standard deviation of about 50. That gap is another sign of a long tail.
Choosing your own percentiles
The default quartiles hide the tail. Pass a percentiles list to look further out.
print(df["Fare"].describe(percentiles=[0.01, 0.05, 0.5, 0.95, 0.99]))Pandas always includes the 50% row even if you leave it out. Comparing the 95% and 99% values with the maximum shows how much of the range is occupied by a handful of passengers. If the 99th percentile is far below the maximum, the maximum is an outlier in the plain sense of "far from the rest." That alone does not make it an error.
Targeted summaries with agg
describe() always prints the same eight statistics. To choose your own, use agg on selected columns.
summary = df[["Age", "Fare"]].agg(["count", "mean", "median", "std", "min", "max", "skew"])
print(summary)Here skew measures asymmetry. A value near 0 means roughly symmetric. A large positive value means a long right tail. Fare has a skew of about 4.8, while Age is under 0.5.
Individual methods such as df["Age"].mean(), .median(), and .std() work the same way. All of them skip missing values by default (skipna=True). That is convenient, but it also means a mean can silently describe only part of your data. Always read the mean next to its count.
Decision: which statistic to report
Numeric columns that are really categories
Survived is 0 or 1, so its mean (about 0.384) is the proportion of survivors. That is a useful trick, and the later groupby chapter relies on it. The std, 25%, and 50% rows for Survived are meaningless.
Pclass is stored as 1, 2, or 3, and its mean of about 2.31 is hard to interpret. Class 2 is not "halfway" between 1 and 3 in any measurable sense. PassengerId is just an identifier, and its mean means nothing. For columns like these, use value_counts() (covered in the next chapters) instead of describe().
A quick way to decide is to count distinct values.
print(df[["PassengerId", "Survived", "Pclass", "SibSp", "Parch", "Age", "Fare"]].nunique())A column with 2 or 3 distinct values is almost certainly a category. A column with as many distinct values as rows is an identifier.
Common errors
- Reading the mean without the count.
Agehas 177 missing values. If missingness is related to who survived or which class they traveled in, the mean may not describe all passengers. - Trusting the mean of a skewed column. Check the median and the high percentiles first.
- Treating
describe()output as the complete picture. Two columns can have identical summaries and very different shapes. Plot the distribution too (a later chapter). - Forgetting that text columns are skipped.
df.describe()ignoresName,Sex,Ticket,Cabin, andEmbarked. Usedf.describe(include="object")for those. - Deleting zero fares automatically. First find out how many there are with
(df["Fare"] == 0).sum(). Roughly 15 passengers have a zero fare. Decide what to do only after you know what the zeros are likely to mean.
Recording what you saw
Write down observations as you go, with the numbers attached. For example:
Agehas 714 of 891 values present. Mean is about 29.7 and median 28, so it is roughly symmetric.Fareis strongly right-skewed (mean about 32.2, median about 14.5, max about 512).- About 15 passengers have
Fareequal to 0. Cause unknown.
These notes become the starting list of questions for the grouping and plotting chapters.
Exercise
In the Titanic data, Fare has a mean of about 32.20 and a median of about 14.45. What does this gap tell you, which statistic better describes a typical passenger, and which one line of pandas would show how far the top of the distribution extends beyond the 99th percentile?
Show answer
The mean is more than twice the median, so the distribution is skewed to the right: a small number of very high fares pull the mean up. The median is the better description of a typical passenger. To see the tail, use df["Fare"].describe(percentiles=[0.95, 0.99]) and compare the 99% row to the max row. A large gap between them means the maximum is an extreme value far from the rest.
Exercise
Why is calling df.describe() on Pclass and reading its mean of 2.31 a poor way to understand passenger classes, and what should you use instead?
Show answer
Pclass is a category stored as numbers. The distances between 1, 2, and 3 are not meaningful, so the mean and standard deviation do not describe anything real. Use df["Pclass"].value_counts() to see how many passengers are in each class.