Skip to main content

Data analysis · Beginner · 14 min

Describe data with summary statistics that tell the truth

By Padding · Updated 18 Nov 2026
Python 3.15 · pandas 3.1.1 · NumPy 2.5.5 · uv 0.13 (checked on python:3.15-slim)

You will summarise 1,200 generated household incomes with the mean, median, mode, standard deviation, IQR and percentiles, see why the mean misleads on skewed data, compare two districts and write up a figure that carries its spread and count.

On this page

"The average household in Hilltop earns GHS 5,970 a month." That sentence is true for the data in this tutorial, and it is still misleading: about two in three Hilltop households earn less than that. A single number always hides something. Summary statistics are useful when you choose the ones that fit the shape of the data and report them with the spread and the count beside them.

You will work on generated survey data from two invented districts, Riverside and Hilltop: 1,200 households, each with a household size and a monthly income in Ghana cedis (GHS). Incomes are skewed, as they are almost everywhere: most households earn a modest amount and a few earn many times more. Some households declined to answer. By the end you will have a short written summary you could hand to someone who will never see the data.

Everything runs in a throwaway folder, ~/summary-stats-demo, which you can delete at the end.

Step 1 · Create the project and generate the survey

Make the folder and add pandas and NumPy. The version ranges allow patch releases only, so a new minor version cannot shift your numbers:

Bash
mkdir -p ~/summary-stats-demo
cd ~/summary-stats-demo
uv init --no-package --python 3.15
uv add "pandas>=3.1,<3.2" "numpy>=2.5,<2.6"
uv run python -c "import pandas, numpy; print(pandas.__version__, numpy.__version__)"

Now write make_incomes.py. The random generator is seeded, so you get the same 1,200 households every time you run it:

Bash
cat > make_incomes.py <<'PY'
import numpy as np
import pandas as pd

rng = np.random.default_rng(1234)
n = 1200

district = rng.choice(["Riverside", "Hilltop"], size=n, p=[0.55, 0.45])
riverside = district == "Riverside"

# Monthly household income in Ghana cedis (GHS). Incomes are right-skewed:
# most households earn a modest amount and a few earn far more.
income = np.where(
    riverside,
    rng.lognormal(mean=np.log(3000), sigma=0.55, size=n),
    rng.lognormal(mean=np.log(3400), sigma=0.85, size=n),
).round(-1)

# A handful of very high earners, all in Hilltop.
rich = rng.choice(np.flatnonzero(~riverside), size=5, replace=False)
income[rich] = rng.uniform(60_000, 150_000, size=5).round(-3)

household_size = np.clip(rng.poisson(3.0, size=n) + 1, 1, 10)

df = pd.DataFrame({
    "household_id": [f"H{i:04d}" for i in range(1, n + 1)],
    "district": district,
    "household_size": household_size,
    "income_ghs": income,
})

# Some households declined to give their income.
declined = rng.choice(n, size=36, replace=False)
df.loc[declined, "income_ghs"] = np.nan

df.to_csv("incomes.csv", index=False)
print("rows:", len(df))
print(df.head().to_string(index=False))
PY
uv run make_incomes.py

Check it worked

The version line prints 3.1.1 2.5.5, or later patch releases. The script prints rows: 1200 and five households. The first is H0001 in Hilltop, two people, GHS 6,510 a month; the third, H0003, is one of the planted high earners at GHS 115,000. A file incomes.csv now sits in the folder.

Step 2 · Find the centre three ways

"Typical" has three common meanings. The mean adds everything up and divides by the count. The median is the middle value once you sort them: half the households earn less, half earn more. The mode is the most frequent value. Write centre.py to compute all three:

Bash
cat > centre.py <<'PY'
import pandas as pd

df = pd.read_csv("incomes.csv")
income = df["income_ghs"]

mean = income.mean()
median = income.median()
print(f"mean income:   {mean:,.0f}")
print(f"median income: {median:,.0f}")

# The mode suits counts and categories, not exact money amounts.
print("most common household size:", df["household_size"].mode().tolist())
print("distinct income values:", income.nunique(), "of", income.count())

# Round to the nearest 500 to find the most common income band.
bands = (income / 500).round() * 500
print(f"most common income band: {bands.mode().iloc[0]:,.0f}")

below = (income < mean).mean()
print(f"households earning less than the mean: {below:.0%}")
PY
uv run centre.py

The mean is GHS 4,609 and the median GHS 3,070. That gap is the signature of right-skewed data: the few large incomes pull the mean up, while the median only cares about which value sits in the middle. Here 69% of households earn less than the "average", which is not what most readers picture when they hear the word.

The mode needs care. On exact money amounts it is close to meaningless: there are 630 distinct incomes among 1,164 answers, so the "most common" one wins by a tie or two. It works on whole-number counts such as household size, and on incomes once you group them into bands. The most common band here is the one around GHS 2,000 (1,750 to 2,249), below both the median and the mean. Mode below median below mean is the usual order for right-skewed data.

mean() and median() skip missing values without telling you, which is why the count of answers (1,164, not 1,200) is worth printing.

Check it worked

The script prints a mean of 4,609, a median of 3,070, a most common household size of [4], 630 distinct incomes of 1164, a most common band of 2,000, and 69% of households below the mean.

Step 3 · Measure the spread

A centre without a spread tells half the story. Three measures are worth knowing:

  • The standard deviation is roughly the typical distance from the mean. pandas uses the sample version, which divides by n − 1.
  • The interquartile range (IQR) is Q3 minus Q1: the width of the middle half of the data, from the 25th to the 75th percentile.
  • Percentiles say what share of values fall below a figure. The 90th percentile is the income that 90% of households fall below.

Write spread.py:

Bash
cat > spread.py <<'PY'
import pandas as pd

df = pd.read_csv("incomes.csv")
income = df["income_ghs"]

q1, q3 = income.quantile([0.25, 0.75])
print(f"standard deviation: {income.std():,.0f}")
print(f"Q1 {q1:,.0f}  Q3 {q3:,.0f}  IQR {q3 - q1:,.0f}")

pct = income.quantile([0.10, 0.25, 0.50, 0.75, 0.90, 0.99])
for p, value in pct.items():
    print(f"  p{round(p * 100):<3} {value:>9,.0f}")
print(f"min {income.min():,.0f}  max {income.max():,.0f}")
PY
uv run spread.py

The standard deviation is GHS 8,389, larger than the mean itself. "Mean plus or minus one standard deviation" would run from about −3,780 to 13,000, and nobody earns a negative income. On skewed data the standard deviation is still a correct number, but it does not describe a range you can picture.

The percentiles do. The middle half of households earn between GHS 1,940 and 5,030. The bottom tenth earn under 1,330, and the top tenth over 8,044. The jump from the 90th percentile (8,044) to the 99th (25,031) to the maximum (144,000) shows how long the right tail is.

quantile() interpolates between neighbouring values by default, which is why some percentiles, such as 8,044, are not multiples of 10 even though every income is.

Check it worked

The script prints a standard deviation of 8,389, then Q1 1,940 Q3 5,030 IQR 3,090, a table of percentiles from p10 (1,330) to p99 (25,031), and min 250 max 144,000.

Step 4 · See how one household moves the mean

The quickest way to feel the difference between these measures is to add one extreme value and watch what changes. Write one_household.py, which adds a single household earning GHS 2 million a month:

Bash
cat > one_household.py <<'PY'
import pandas as pd

income = pd.read_csv("incomes.csv")["income_ghs"].dropna()

# Add one household that earns GHS 2 million a month.
with_one = pd.concat([income, pd.Series([2_000_000.0])], ignore_index=True)

rows = []
for name, s in {"survey": income, "plus one rich household": with_one}.items():
    q1, q3 = s.quantile([0.25, 0.75])
    rows.append({
        "data": name,
        "n": len(s),
        "mean": round(s.mean()),
        "median": round(s.median()),
        "std": round(s.std()),
        "iqr": round(q3 - q1),
    })
print(pd.DataFrame(rows).to_string(index=False))
PY
uv run one_household.py

One household out of 1,165 lifts the mean by more than a third, from 4,609 to 6,322, and multiplies the standard deviation by seven. The median and the IQR do not move at all. Statisticians call the median and IQR robust: a few extreme values, real or mistaken, cannot drag them far.

That does not make the mean wrong. If you need a total (how much the district earns, how much tax it could raise), the mean times the count is exactly right. For "what does a typical household earn?", use the median.

Check it worked

The table has two rows. survey shows n 1164, mean 4609, median 3070, std 8389 and IQR 3090. plus one rich household shows n 1165, mean 6322, median 3070, std 59059 and IQR 3090: only the mean and the standard deviation changed.

Step 5 · Read describe() with care

describe() prints most of these statistics in one call, which makes it the first thing many people run on a new dataset. It is a good habit, as long as you read every line rather than glancing at the mean. Write describe.py:

Bash
cat > describe.py <<'PY'
import pandas as pd

df = pd.read_csv("incomes.csv")
print("rows in file:", len(df))
print()
print(df.describe().round(1).to_string())
print()
print(df["district"].describe().to_string())
print()
print(df["income_ghs"].describe(percentiles=[0.1, 0.5, 0.9]).round(0).to_string())
PY
uv run describe.py

Go through the first table line by line, asking what each one tells you:

  • count is 1200 for household size but 1164 for income. count leaves out missing values, so 36 households have no income. If you only read the mean, you would never know.
  • mean against 50% (the median): 4.0 and 4.0 for household size, so that column is roughly symmetric. 4,609 against 3,070 for income, so income is skewed and the mean is not the typical value.
  • std is 8,388.7 for income, more than the mean: another sign of a long tail, as you saw in the last step.
  • min and max: 250 is a plausible low income; 144,000 is 47 times the median. That is worth a look, which is what the outliers tutorial is about.

Notice what is missing. describe() on a whole DataFrame covers numeric columns only, so household_id and district do not appear. Called on a text column, it gives a different summary: count, unique (2 districts), top (the most common, Riverside) and freq (647 households). The percentiles argument replaces the default 25%, 50% and 75% with the ones you ask for; the median always stays in.

Check it worked

The first table has count 1200.0 1164.0, mean 4.0 4609.3, 50% 4.0 3070.0 and max 10.0 144000.0. The district summary shows top Riverside and freq 647. The last summary has rows for 10%, 50% and 90%, with 90% 8044.0.

Step 6 · Compare the two districts with the same statistics

Comparing groups is where a single average does the most damage. Put the same statistics side by side for each district, and include the counts so the reader knows how many households stand behind each figure. Write groups.py:

Bash
cat > groups.py <<'PY'
import pandas as pd

df = pd.read_csv("incomes.csv")

def q1(s):
    return s.quantile(0.25)

def q3(s):
    return s.quantile(0.75)

summary = df.groupby("district")["income_ghs"].agg(
    households="size",
    answered="count",
    mean="mean",
    median="median",
    q1=q1,
    q3=q3,
    p90=lambda s: s.quantile(0.90),
)
summary["iqr"] = summary["q3"] - summary["q1"]
print(summary.round(0).astype(int).to_string())
PY
uv run groups.py

size counts every row in the group and count only the ones with an income, so the first two columns show how many households were asked and how many answered.

Now compare. By the mean, Hilltop households earn GHS 2,506 more a month than Riverside ones. By the median, the gap is GHS 530. The lower quartiles are almost the same (1,938 and 1,950), so the poorer quarter of households look alike in both districts. The difference is in the top half: Hilltop's 90th percentile is 10,863 against Riverside's 6,305, and its IQR is two-thirds wider. "Hilltop is richer" is true at the top and close to false at the bottom. Only the spread tells you that.

When incomes come from farming, trading or other work paid irregularly, a single month can swing a long way between harvest and lean season. Say which month or period a survey covers, and be cautious comparing districts surveyed at different times of year.

Check it worked

The table has one row per district. Hilltop: 553 households, 532 answered, mean 5970, median 3425, IQR 4142. Riverside: 647 households, 632 answered, mean 3464, median 2895, IQR 2475.

Step 7 · Report a figure with its spread and count

A good written figure answers three questions at once: what is typical, how much does it vary, and how many cases is it based on. Write report.py, which turns the summary into a few sentences in a Markdown file:

Bash
cat > report.py <<'PY'
import pandas as pd

df = pd.read_csv("incomes.csv")
answered = df.dropna(subset=["income_ghs"])

lines = ["# Monthly household income, survey of 2026", ""]
for district, group in answered.groupby("district"):
    s = group["income_ghs"]
    q1, q3 = s.quantile([0.25, 0.75])
    asked = int((df["district"] == district).sum())
    lines.append(
        f"- {district}: median GHS {s.median():,.0f}"
        f" (middle half GHS {q1:,.0f} to {q3:,.0f}),"
        f" mean GHS {s.mean():,.0f}; n = {len(s)} of {asked} households"
    )
lines += [
    "",
    f"{len(df) - len(answered)} households did not give an income and are left out.",
    "Incomes are skewed, so the median is the headline figure.",
]
text = "\n".join(lines) + "\n"
with open("report.md", "w", encoding="utf-8") as f:
    f.write(text)
print(text, end="")
PY
uv run report.py

Each line leads with the median, gives the middle half as the spread, keeps the mean for anyone who needs totals, and says how many households answered out of how many were asked. The closing lines say what was left out and why the median is the headline. Because every number is computed from the file, re-running the script after a correction updates the report with no copying by hand.

When you finish, delete the practice folder with rm -r ~/summary-stats-demo. Check the path first: it removes everything inside it.

Check it worked

report.md exists and has two bullet lines. Hilltop: median GHS 3,425, middle half 1,938 to 6,080, mean 5,970, n = 532 of 553. Riverside: median GHS 2,895, middle half 1,950 to 4,425, mean 3,464, n = 632 of 647. Below them is the line 36 households did not give an income and are left out.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.