Sign in

Summary statistics

The first look at a new table: its shape, each column's type and missing values, and summary statistics for every column.

Overview

Before any analysis, check that the table is what you think it is. How many rows and columns are there? Is each column a number, text or something else? How many values are missing? Then get a short summary of each column. For a numeric column that is the count, mean, standard deviation, smallest value, quartiles and largest value. For a text column it is the count, the number of different values, the most common value and how often it occurs. A glance at these catches most early problems: an age of 999, a price column read as text, a column that is half empty. The folder is named after pandas, but the code uses NumPy and the standard library on a plain dict of columns, and the numbers match pandas' conventions.

A short history

Summarising a table by counts, means and quantiles is as old as official statistics. John Tukey's five number summary of 1977 fixed a compact form for one column. The habit of starting every analysis with shape, column types and a describe call comes from data frame software: the S language and R from the 1970s to the 1990s, and the pandas library that Wes McKinney began in 2008 and released as open source in 2009.

How it works

  1. Hold the table as a dict that maps each column name to a list of values. Use from_rows to build it from a list of row dicts, where absent keys become None.
  2. Call structure to get the number of rows and columns and, for each column, its inferred type and its count of missing values.
  3. For each numeric column, describe computes count, mean, standard deviation (with the configured ddof), minimum, the configured percentiles and maximum, over the present values.
  4. For each other column, describe computes count, number of distinct values, the most frequent value and its frequency.
  5. The include setting restricts describe to all, numeric or categorical columns.
  6. Call to_text to render the result as an aligned table, one row per statistic.

Watch out for

  • Summary statistics hide shape. Very different datasets can share the same mean, standard deviation and quartiles, so plot the columns as well.
  • The count excludes missing values, so two columns of the same table can have different counts. Compare each count with the number of rows.
  • A numeric column stored as text is summarised as categorical, with no mean or quartiles. That is a sign the data need cleaning, not a property of the column.
  • A mean and standard deviation are computed for any numeric column, including identifier codes where they mean nothing.
  • The minimum and maximum are single values and may be data-entry errors. Treat them as questions to check, not as the range of the data.

Use cases

When to use it

Right after loading data: to check that the table has the rows, columns and types you expect, to spot missing values and impossible minimums or maximums, and to learn the scale of each numeric column.

In industry

Any analytics team
The first step with a new extract is to check row and column counts, types and missing values so that loading errors are found before analysis starts.
Finance operations
Reconciliation staff compare totals, minimums and maximums of a ledger extract with control figures to confirm the file is complete.
Machine learning
Before training, engineers inspect per feature ranges and missing rates to spot constant columns, wrong units and impossible values.

Choosing it: what must hold

  • Data loaded into a table with one row per observation and one column per variable.
  • Column types parsed correctly, since numbers read as text produce no numeric summary.
  • An understanding that a summary describes columns one at a time and says nothing about relationships.

When to choose something else

IfUse instead
You need cardinality, schema checks and leakage detectionData profiling
You need the shape of a column, not only its centre and spreadDistribution analysis
You need to know how columns relateCorrelation or association analysis

Math foundations

  1. Mean

    xˉ=1n∑i=1nxi\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i

    The sum of the present values divided by their count. It gives the centre of the column and is pulled by extreme values.

  2. Sample standard deviation

    s=1n−1∑i=1n(xi−xˉ)2s = \sqrt{\frac{1}{n - 1} \sum_{i=1}^{n} (x_i - \bar{x})^{2}}

    The typical distance of a value from the mean. The divisor n−1n - 1 is the pandas default and matches ddof set to 1.

  3. Linear quantile

    h=(n−1) p+1,Q(p)=x(⌊h⌋)+(h−⌊h⌋)(x(⌊h⌋+1)−x(⌊h⌋))h = (n - 1)\,p + 1, \qquad Q(p) = x_{(\lfloor h \rfloor)} + \big(h - \lfloor h \rfloor\big)\big(x_{(\lfloor h \rfloor + 1)} - x_{(\lfloor h \rfloor)}\big)

    The value below which a share pp of the sorted data lies. The position hh counts from 1, and the quantile is interpolated between the two sorted values around it. The 25, 50 and 75 percent rows of the summary are Q(0.25)Q(0.25), Q(0.5)Q(0.5) and Q(0.75)Q(0.75).

Symbols

xix_i
the i-th present (non-missing) value of the column
nn
count of present values
xˉ\bar{x}
the mean
ss
the sample standard deviation
pp
the quantile level, between 0 and 1
hh
position of the quantile in the sorted values, counted from 1
x(k)x_{(k)}
the k-th smallest value

Worked by hand

A column x holds 1, 2, 3, 4, 5. Reproduce its row of the summary by hand.

xˉ=1+2+3+4+55=3\bar{x} = \frac{1 + 2 + 3 + 4 + 5}{5} = 3
s=4+1+0+1+45−1=2.5=1.5811s = \sqrt{\frac{4 + 1 + 0 + 1 + 4}{5 - 1}} = \sqrt{2.5} = 1.5811
Q(0.25):  h=4×0.25+1=2  ⇒  x(2)=2Q(0.25): \; h = 4 \times 0.25 + 1 = 2 \;\Rightarrow\; x_{(2)} = 2
Q(0.75):  h=4×0.75+1=4  ⇒  x(4)=4Q(0.75): \; h = 4 \times 0.75 + 1 = 4 \;\Rightarrow\; x_{(4)} = 4

Count 5, mean 3, standard deviation 1.5811, minimum 1, quartiles 2, 3 and 4, maximum 5. These are the values describe returns.

Visual example

Loading the example.

Try this

  • Type the word unknown into one age cell: the column turns mixed and loses its mean and quartiles.
  • Empty an income cell and watch the count drop while the mean is taken over the values that remain.
  • Change the income in row 5 to 720000 and compare how far the mean and the 50% row move.

Code sample

from impl import SummaryStatistics
from config import SummaryStatisticsConfig

rows = [{"x": 1, "city": "Rome"}, {"x": 2, "city": "Oslo"}, {"x": 3, "city": "Rome"}, {"x": 4}, {"x": 5, "city": "Rome"}]
table = SummaryStatistics.from_rows(rows)
stats = SummaryStatistics(SummaryStatisticsConfig(percentiles=(0.25, 0.5, 0.75)))
print(stats.structure(table))        # 5 rows, 2 columns, x: int, city: str with 1 null
summary = stats.describe(table)      # x: count 5, mean 3.0, std 1.5811, min 1, 25% 2, 50% 3, 75% 4, max 5
print(SummaryStatistics.to_text(summary))
Read the implementation (138 lines)
"""Summary statistics of a table: its structure, the type of each column, and per-column summaries.

NumPy and the standard library only (no pandas). A table is a dict {column name: sequence of values}, all of the
same length; `from_rows` builds one from a list of row dicts. `structure` answers what DataFrame.info() answers and
`describe` what DataFrame.describe() answers, with the same statistics and the same quantile rule.
"""
from __future__ import annotations

import math
from collections import Counter

import numpy as np

try:
    from .config import SummaryStatisticsConfig
except ImportError:  # run from the template's own folder
    from config import SummaryStatisticsConfig

NUMERIC = ("int", "float")


def _is_missing(value) -> bool:
    return value is None or (isinstance(value, (float, np.floating)) and math.isnan(value))


class SummaryStatistics:
    """Shape, column types and summary statistics of a table held as a dict of sequences."""

    def __init__(self, config: SummaryStatisticsConfig | None = None) -> None:
        self.config = config or SummaryStatisticsConfig()

    @staticmethod
    def from_rows(rows: list[dict]) -> dict:
        """Turn a list of row dicts into a table {column: list of values}; absent keys become None."""
        names: list[str] = []
        for row in rows:
            names.extend(k for k in row if k not in names)
        return {name: [row.get(name) for row in rows] for name in names}

    @staticmethod
    def _present(values) -> list:
        return [v.item() if isinstance(v, np.generic) else v for v in values if not _is_missing(v)]

    @staticmethod
    def _n_rows(columns: dict) -> int:
        lengths = {len(v) for v in columns.values()}
        if len(lengths) > 1:
            raise ValueError(f"columns must all have the same length, got lengths {sorted(lengths)}")
        return lengths.pop() if lengths else 0

    def dtype(self, values) -> str:
        """"bool", "int", "float", "str", "mixed" (several kinds of value) or "empty" (only missing values)."""
        present = self._present(values)
        if not present:
            return "empty"
        kinds = {
            "bool" if isinstance(v, bool) else "int" if isinstance(v, int) else "float" if isinstance(v, float)
            else "str" if isinstance(v, str) else "mixed"
            for v in present
        }
        if kinds == {"int", "float"}:
            return "float"
        return kinds.pop() if len(kinds) == 1 else "mixed"

    def structure(self, columns: dict) -> dict:
        """Shape and per-column type and completeness.

        Returns {"n_rows", "n_columns", "columns": [{"name", "dtype", "non_null", "null"}, ...]} in column order.
        """
        n_rows = self._n_rows(columns)
        described = []
        for name, values in columns.items():
            non_null = len(self._present(values))
            described.append({"name": name, "dtype": self.dtype(values), "non_null": non_null, "null": n_rows - non_null})
        return {"n_rows": n_rows, "n_columns": len(columns), "columns": described}

    def describe_numeric(self, values) -> dict:
        """count, mean, std, min, the configured percentiles, and max of one numeric column; missing values skipped."""
        x = np.array(self._present(values), dtype=float)
        out: dict = {"count": int(x.size)}
        if x.size == 0:
            return out
        out["mean"] = float(x.mean())
        out["std"] = float(x.std(ddof=self.config.ddof)) if x.size > self.config.ddof else float("nan")
        out["min"] = float(x.min())
        for p in sorted(self.config.percentiles):
            out[f"{p * 100:g}%"] = float(np.quantile(x, p))
        out["max"] = float(x.max())
        return out

    def describe_categorical(self, values) -> dict:
        """count, unique, top (most frequent value; ties go to the first seen) and freq (its count)."""
        present = self._present(values)
        out: dict = {"count": len(present), "unique": len(set(map(repr, present)))}
        if present:
            (top, freq), = Counter(present).most_common(1) if self._hashable(present) else [(present[0], 1)]
            out["top"], out["freq"] = top, freq
        return out

    @staticmethod
    def _hashable(values: list) -> bool:
        try:
            set(values)
            return True
        except TypeError:
            return False

    def describe(self, columns: dict) -> dict:
        """Summary of every column selected by config.include. Returns {column: {statistic: value}}.

        Numeric columns ("int", "float") get describe_numeric, all others describe_categorical.
        """
        self._n_rows(columns)
        out = {}
        for name, values in columns.items():
            numeric = self.dtype(values) in NUMERIC
            if numeric and self.config.include in ("all", "numeric"):
                out[name] = self.describe_numeric(values)
            elif not numeric and self.config.include in ("all", "categorical"):
                out[name] = self.describe_categorical(values)
        return out

    @staticmethod
    def to_text(description: dict, digits: int = 4) -> str:
        """Render the result of `describe` as an aligned text table: one row per statistic, one column per column."""
        statistics: list[str] = []
        for stats in description.values():
            statistics.extend(s for s in stats if s not in statistics)

        def cell(value) -> str:
            if value is None:
                return ""
            return f"{value:.{digits}g}" if isinstance(value, float) else str(value)

        header = [""] + list(description)
        rows = [[s] + [cell(description[c].get(s)) for c in description] for s in statistics]
        widths = [max(len(r[i]) for r in [header] + rows) for i in range(len(header))]
        return "\n".join("  ".join(v.rjust(w) if i else v.ljust(w) for i, (v, w) in enumerate(zip(r, widths))) for r in [header] + rows)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Build a table with SummaryStatistics.from_rows from five row dicts that have a numeric key x and a text key city, leaving city out of one row. Call structure and find the missing value, then describe and print it with SummaryStatistics.to_text. Change one x to the text "4" and see how the column's type and summary change.

Check on learning

  1. A column's mean is 48 and its median (the 50 percent row) is 12. Without plotting, what can you say about its shape, and which further rows of the summary would confirm it?
    A way to think about it

    Ask what pulls a mean far above the middle value. Then compare the distance from the 75 percent row to the maximum with the distance from the minimum to the 25 percent row.

  2. The table has 10 000 rows but one column has a count of 6200. What should you find out before using that column?
    A way to think about it

    Missing values are rarely random. Check whether the missing rows share a date, a source or a value of another column.

  3. The minimum of an age column is -1 and the maximum is 999. What are these likely to be, and why does the summary statistics step catch them where a model would not?
    A way to think about it

    Systems often write special codes for unknown. A model treats them as real ages and adjusts quietly.

  4. Two columns have identical count, mean, standard deviation and quartiles. Could they still look completely different on a chart?
    A way to think about it

    Eight numbers cannot pin down a shape. Think of one column with a single peak and one with two peaks placed to give the same quartiles.

  5. A customer id column is numeric, so describe reports its mean. How should you decide which numeric columns deserve numeric summaries?
    A way to think about it

    Ask whether adding two values of the column gives something meaningful. Compare with the number of distinct values relative to the row count.