Sign in

Data types

Levels of measurement: nominal, ordinal, interval and ratio

The four levels of measurement (nominal, ordinal, interval, ratio) decide which statistics are meaningful for a column.

Overview

Not every number means the same kind of thing. A postal code is a label that happens to be written in digits, so its mean is nonsense. Stevens' scheme sorts columns into four levels. Nominal values are labels, such as colour or city. Ordinal values have an order but no fixed distance between steps, such as small, medium, large. Interval values have equal steps but an arbitrary zero, such as degrees Celsius. Ratio values have a true zero that means none of the quantity, such as mass, price or a count. Each level allows everything the level below allows and adds something, so naming the level tells you which summaries you may trust.

A short history

The psychologist Stanley Smith Stevens proposed the four levels of measurement in his 1946 paper On the Theory of Scales of Measurement, published in Science. He was answering a dispute about whether sensations such as loudness could be measured at all, and argued that the permitted statistics depend on which transformations leave the scale's meaning intact. The scheme has been criticised as too rigid, but it remains the standard first classification of a variable.

How it works

  1. Remove missing values: None, NaN and the empty string.
  2. If the config lists an order and every value of the column is in it, the column is ordinal.
  3. Otherwise, if every value is a number (or text that parses as one, when numeric_strings is set), the column is ratio when true_zero is true and interval when it is false.
  4. Anything else is nominal.
  5. Look up the statistics permitted at that level. The list is cumulative: each level keeps what the lower levels allow.
  6. Compute only those statistics with summarize. The ordinal median is the lower middle category, so it is always a real category.

Watch out for

  • Whether a number has a true zero cannot be read from the values. The template takes your word through true_zero, and a wrong setting lets ratio statistics through for interval data.
  • Numeric codes for categories, such as 1 for red and 2 for blue, are inferred as ratio, because they look like numbers. You must mark them as categories yourself.
  • The order of text categories is also your statement. Without it, a column such as low, medium, high is treated as nominal and loses its median.
  • The levels are a guide, not a law. Averages of ordinal ratings are widely used, and they are only meaningful if you accept that the steps are roughly equal.

Use cases

When to use it

At the start of an analysis, to decide which summaries, charts and tests fit each column and to stop meaningless numbers, such as the mean of postal codes, from reaching a report.

In industry

Survey research
Analysts treat a five point agreement scale as ordinal and report medians and rank tests, where treating it as interval would allow means.
Machine learning
The level of each column decides its encoding: one hot codes for nominal categories, ordered integers for ordinal ones, and scaling for interval and ratio features.
Medicine
Pain scores are ordinal, body temperature in Celsius is interval and blood pressure is ratio, which determines whether statements such as twice as high are valid.

Choosing it: what must hold

  • Knowledge of how each variable was recorded and what its values mean, not only its storage type.
  • A decision still to be made about which statistics, charts or encodings to apply.
  • Willingness to check codes stored as numbers, such as postcodes or identifiers, which are nominal in spite of their type.

When to choose something else

IfUse instead
You only need the storage types and missing counts of a tableSummary statistics or data profiling
The variable is a count, a proportion or a circular quantity such as an angleA finer typology, treating counts, bounded and circular data with models built for them

Math foundations

  1. Nominal: relabelling

    x′=f(x),f one-to-onex' = f(x), \qquad f \text{ one-to-one}

    Labels can be renamed in any way that keeps different things different. Only statements that survive every such renaming are meaningful: counts and the mode.

  2. Ordinal: order-preserving change

    x′=f(x),a<b  ⇒  f(a)<f(b)x' = f(x), \qquad a < b \;\Rightarrow\; f(a) < f(b)

    Any change that keeps the order is allowed. The median and percentiles survive it, because they depend on order alone. The mean does not.

  3. Interval: shift and scale

    x′=a x+b,a>0x' = a\,x + b, \qquad a > 0

    The zero point and the unit are both arbitrary, as with Celsius and Fahrenheit. Means and standard deviations transform consistently, and differences can be compared. Ratios of values cannot.

  4. Ratio: scale only

    x′=a x,a>0,x1′x2′=x1x2x' = a\,x, \qquad a > 0, \qquad \frac{x_1'}{x_2'} = \frac{x_1}{x_2}

    Only the unit is arbitrary, since zero is fixed. Ratios of values are the same in every unit, which is what makes statements like twice as heavy meaningful.

  5. Geometric mean

    G=(∏i=1nxi)1/n=exp⁡ ⁣(1n∑i=1nln⁡xi)G = \left(\prod_{i=1}^{n} x_i\right)^{1/n} = \exp\!\left(\frac{1}{n} \sum_{i=1}^{n} \ln x_i\right)

    A statistic that needs the ratio level: it multiplies values, so it requires a true zero and positive values. It is the right average for growth factors.

Symbols

xx
a value as recorded
x′x'
the same value after a permitted change of labels or units
ff
the function that makes the change
a,ba, b
the scale factor and the shift of a change of units
GG
the geometric mean
nn
number of values

Worked by hand

Two afternoons measure 10 and 20 degrees Celsius. Converting to Fahrenheit uses x′=1.8x+32x' = 1.8x + 32. Is the second afternoon twice as warm?

2010=2in Celsius\frac{20}{10} = 2 \quad \text{in Celsius}
x1′=1.8×10+32=50,x2′=1.8×20+32=68x_1' = 1.8 \times 10 + 32 = 50, \qquad x_2' = 1.8 \times 20 + 32 = 68
6850=1.36in Fahrenheit\frac{68}{50} = 1.36 \quad \text{in Fahrenheit}
x2′−x1′=18=1.8×(20−10)x_2' - x_1' = 18 = 1.8 \times (20 - 10)

The ratio changes with the unit, so twice as warm is not a meaningful statement on an interval scale. The difference changes only by the scale factor, so differences are meaningful.

Visual example

Loading the example.

Try this

  • With the temperature column, set a to 1.8 and b to 32 to convert to Fahrenheit: the ratio of two values changes, the ratio of two gaps does not.
  • Choose blood group and click Interval in the diagram: the computation refuses a mean of labels.
  • Choose shirt size and step the level from Nominal to Ordinal to see the median, minimum and maximum appear.

Code sample

from impl import MeasurementScale
from config import MeasurementScaleConfig

sizes = MeasurementScale(MeasurementScaleConfig(order=("small", "medium", "large")))
print(sizes.infer(["small", "large", "medium"]))                 # ordinal
print(sizes.summarize(["small", "large", "medium"])["median"])   # medium
print(MeasurementScale.allows("mean", "ordinal"))                # False
print(MeasurementScale().summarize([1.0, 2.0, 4.0])["geometric_mean"])  # 2.0
Read the implementation (139 lines)
"""Levels of measurement (Stevens): nominal, ordinal, interval, ratio.

Each level allows every statistic of the level below it plus some of its own. This template infers the level of a
column, answers "may I compute this statistic here?", and summarises a column with only the statistics its level
permits. NumPy and the standard library only.
"""
from __future__ import annotations

import math
from collections import Counter

import numpy as np

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

LEVELS = ("nominal", "ordinal", "interval", "ratio")

_OWN = {
    "nominal": ("count", "n_unique", "mode", "frequencies"),
    "ordinal": ("median", "min", "max"),
    "interval": ("mean", "std", "range"),
    "ratio": ("geometric_mean", "coefficient_of_variation"),
}
# PERMISSIBLE[level] lists every statistic that is meaningful at that level (cumulative up the ladder).
PERMISSIBLE = {level: tuple(s for lower in LEVELS[: i + 1] for s in _OWN[lower]) for i, level in enumerate(LEVELS)}


def _is_missing(value) -> bool:
    if value is None:
        return True
    if isinstance(value, float) and math.isnan(value):
        return True
    return isinstance(value, str) and value.strip() == ""


def _as_number(value, numeric_strings: bool):
    """The value as a float, or None when it is not a number. Booleans are categories, not numbers."""
    if isinstance(value, (bool, np.bool_)):
        return None
    if isinstance(value, (int, float, np.integer, np.floating)):
        return float(value)
    if numeric_strings and isinstance(value, str):
        try:
            return float(value)
        except ValueError:
            return None
    return None


class MeasurementScale:
    """Infers a column's level of measurement and computes only the statistics that level permits."""

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

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

    def _numbers(self, values: list) -> np.ndarray | None:
        numbers = [_as_number(v, self.config.numeric_strings) for v in values]
        return None if any(n is None for n in numbers) else np.array(numbers, dtype=float)

    def infer(self, values) -> str:
        """Level of measurement of a column. values: sequence of length n; None, NaN and "" are missing.

        Numbers are "ratio" (or "interval" when config.true_zero is false). Anything else is "ordinal" when
        config.order lists its categories and "nominal" otherwise. Whether a number has a true zero cannot be
        read from the data, so that part is the caller's statement, made through the config.
        """
        clean = self._clean(values)
        if not clean:
            raise ValueError("values holds no data")
        if self.config.order is not None and all(v in self.config.order for v in clean):
            return "ordinal"
        if self._numbers(clean) is not None:
            return "ratio" if self.config.true_zero else "interval"
        return "nominal"

    @staticmethod
    def permissible(level: str) -> tuple:
        """Names of the statistics that are meaningful at `level`."""
        if level not in LEVELS:
            raise ValueError(f"level must be one of {LEVELS}, got {level!r}")
        return PERMISSIBLE[level]

    @staticmethod
    def allows(statistic: str, level: str) -> bool:
        """True when `statistic` (for example "mean") is meaningful at `level`."""
        return statistic in MeasurementScale.permissible(level)

    def summarize(self, values, level: str | None = None) -> dict:
        """Summary of a column holding exactly the statistics its level permits.

        values: sequence of length n. level: one of LEVELS, or None to infer it.
        The ordinal median is the lower middle value in category order, so it is always a real category.
        """
        clean = self._clean(values)
        level = level or self.infer(values)
        allowed = self.permissible(level)
        if not clean:
            raise ValueError("values holds no data")
        numbers = self._numbers(clean)
        if level in ("interval", "ratio"):
            if numbers is None:
                raise ValueError(f"a {level} column must be numeric")
            clean = numbers.tolist()
        counts = Counter(clean)
        top = max(counts.values())
        out = {
            "level": level,
            "count": len(clean),
            "n_unique": len(counts),
            "mode": sorted((v for v, c in counts.items() if c == top), key=self._sort_key(level))[0],
            "frequencies": dict(counts),
        }
        if "median" in allowed:
            ordered = sorted(clean, key=self._sort_key(level))
            out["min"], out["max"] = ordered[0], ordered[-1]
            out["median"] = float(np.median(numbers)) if level != "ordinal" else ordered[(len(ordered) - 1) // 2]
        if "mean" in allowed:
            out["mean"] = float(numbers.mean())
            out["std"] = float(numbers.std(ddof=1)) if numbers.size > 1 else 0.0
            out["range"] = float(numbers.max() - numbers.min())
        if "geometric_mean" in allowed:
            out["geometric_mean"] = float(np.exp(np.log(numbers).mean())) if (numbers > 0).all() else None
            out["coefficient_of_variation"] = out["std"] / abs(out["mean"]) if out["mean"] != 0 else None
        return out

    def _sort_key(self, level: str):
        """Sorting key for one level: position in config.order for ordinal data, the value itself otherwise."""
        order = self.config.order
        if level == "ordinal" and order is not None:
            return lambda v: order.index(v)
        if level == "nominal":
            return lambda v: str(v)
        return lambda v: v
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create MeasurementScale(MeasurementScaleConfig(order=("small", "medium", "large"))) and call infer and summarize on a list of sizes. Call MeasurementScale.allows("mean", "ordinal"). Then summarize a list of Celsius temperatures twice, once with true_zero left true and once set to false, and list the statistics that disappear.

Check on learning

  1. A survey codes answers as 1 (disagree) to 5 (agree). What do you assume about the answers if you report their mean, and how could that assumption fail?
    A way to think about it

    The mean treats the step from 1 to 2 as equal to the step from 4 to 5. Ask whether respondents experience them as equal.

  2. Why is the coefficient of variation allowed for prices but not for calendar years?
    A way to think about it

    It divides by the mean. Consider what happens to the mean of a set of years if the calendar started at a different point.

  3. A column holds the values 1, 2 and 3 for three hospital wards. The template infers ratio. What would a model or a summary do wrong with it, and how do you prevent that?
    A way to think about it

    Ask what ward 2 being the average of wards 1 and 3 would mean. Then think about how to store the column so that it is not read as a number.

  4. Kelvin and Celsius measure the same thing. Why is one a ratio scale and the other an interval scale, and which statistics become available when you convert?
    A way to think about it

    Find the transformation between them and check whether it has a shift. Then ask what zero means on each.

  5. Why is the ordinal median defined here as the lower middle category instead of the average of the two middle ones?
    A way to think about it

    Try to average medium and large. The result must be something the scale contains.