Sign in

Coefficient of variation

The coefficient of variation is the standard deviation divided by the absolute mean: spread as a share of the typical size, with no unit.

Overview

A standard deviation of 5 means little until you know the scale. For weights around 10 grams it is huge, and for weights around 10 000 grams it is tiny. Dividing by the mean removes the scale, and the unit cancels as well. A coefficient of variation (CV) of 0.1 says the typical deviation is 10 percent of the mean, whether the data are in grams or kilometres. That makes it possible to compare the variability of quantities that are measured differently. The price is that the ratio only makes sense when zero means none of the quantity and the mean is safely away from zero.

A short history

Karl Pearson introduced the coefficient of variation in 1896, in his work on heredity and biometry, to compare the variability of measurements that have different units or very different sizes, such as the lengths of different organs. Dividing the standard deviation by the mean gives a pure number. It has since become a routine measure of relative precision in laboratories and of relative risk in finance.

How it works

  1. Ignore NaN entries and compute the mean.
  2. Compute the standard deviation with the configured ddof: 1 divides by n−1n - 1 for a sample, 0 divides by nn for a whole population.
  3. Divide the standard deviation by the absolute value of the mean. Where the mean is exactly zero the result is NaN.
  4. If unbiased is set, multiply by 1+1/(4n)1 + 1/(4n), a small-sample correction that holds for normal data.
  5. If as_percent is set, multiply by 100.
  6. For a version that outliers barely move, use quartile_dispersion, which is built from the first and third quartiles.

Watch out for

  • When the mean is near zero the ratio explodes, because a small change in the mean produces a huge change in the CV.
  • On an interval scale such as degrees Celsius the CV is meaningless, because moving the zero point changes the mean but not the spread.
  • If the values straddle zero the mean can cancel to almost nothing while the spread stays large, which gives an enormous and uninformative CV.
  • Both the mean and the standard deviation are pulled by outliers, so a single extreme value can change the CV a lot. The quartile version is the robust alternative.
  • The correction factor 1+1/(4n)1 + 1/(4n) is derived for normal data. On skewed data it is not a guarantee of an unbiased estimate.

Use cases

When to use it

Comparing variability across columns with different units or very different means, such as assay precision, price volatility at different price levels, or the consistency of a process. The data must be on a ratio scale with a true zero.

In industry

Clinical laboratories
Assay precision is reported as a coefficient of variation: repeated measurements of the same sample should vary by only a few percent of the mean.
Inventory planning
Planners compute the coefficient of variation of weekly demand per product to separate steady sellers from erratic ones and set safety stock accordingly.
Finance
Analysts compare investments by volatility per unit of expected return, which is a coefficient of variation.

Choosing it: what must hold

  • Data on a ratio scale with a true zero, such as weight, concentration or revenue.
  • A mean that is clearly away from zero, since the ratio blows up as the mean approaches zero.
  • Values that are all positive, or at least a mean whose sign and size are meaningful.

When to choose something else

IfUse instead
The variable is on an interval scale such as temperature in CelsiusStandard deviation, reported in the original unit
The data are heavily skewed or have outliersA robust ratio such as the interquartile range divided by the median
All groups share the same unit and similar meansStandard deviation or variance directly

Math foundations

  1. 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, in the unit of the data. With ddof set to 0 the divisor is nn instead.

  2. Coefficient of variation

    CV=s∣xˉ∣\mathrm{CV} = \frac{s}{|\bar{x}|}

    Spread relative to size. Numerator and denominator carry the same unit, so it cancels. Multiplying every value by a constant leaves the CV unchanged.

  3. Small-sample correction

    CV∗=(1+14n)CV\mathrm{CV}^{*} = \left(1 + \frac{1}{4n}\right) \mathrm{CV}

    The plain CV runs slightly low on small samples from a normal distribution. This factor compensates and fades to 1 as nn grows.

  4. Quartile coefficient of dispersion

    QCD=Q3−Q1Q3+Q1\mathrm{QCD} = \frac{Q_3 - Q_1}{Q_3 + Q_1}

    A relative spread built from quartiles only. Extreme values do not enter it, so it stays stable when the tails are wild.

Symbols

xix_i
the i-th value
nn
number of values
xˉ\bar{x}
the mean of the values
ss
the standard deviation
Q1,Q3Q_1, Q_3
first and third quartiles

Worked by hand

Eight values treated as a whole population (ddof 0): 2, 4, 4, 4, 5, 5, 7, 9. Their sum is 40.

xˉ=408=5\bar{x} = \frac{40}{8} = 5
∑(xi−xˉ)2=9+1+1+1+0+0+4+16=32\sum (x_i - \bar{x})^{2} = 9 + 1 + 1 + 1 + 0 + 0 + 4 + 16 = 32
s=328=2s = \sqrt{\frac{32}{8}} = 2
CV=25=0.4\mathrm{CV} = \frac{2}{5} = 0.4

The typical deviation is 40 percent of the mean. If every value were in other units, say multiplied by 1000, the CV would still be 0.4.

Visual example

Loading the example.

Try this

  • Multiply every value by 1000: the axis labels change and the CV stays at 0.4.
  • Add 15 to every value: the spread is the same, yet the CV drops because the mean is farther from zero.
  • Add minus 5 to bring the mean to zero and see the CV stop making sense.

Code sample

from impl import CoefficientOfVariation
from config import CoefficientOfVariationConfig

cv = CoefficientOfVariation(CoefficientOfVariationConfig(ddof=0))
print(cv.cv([2, 4, 4, 4, 5, 5, 7, 9]))                    # 0.4
print(cv.quartile_dispersion([1, 2, 3, 4, 5, 6, 7]))      # 0.375
print(cv.compare({"a": [10, 11, 9], "b": [1, 20, 5]}))    # most variable group first
Read the implementation (65 lines)
"""Coefficient of variation: standard deviation relative to the mean.

NumPy only. The CV has no unit, so it compares the spread of quantities measured on different scales.
It only makes sense for ratio-scale data (a true zero, positive values).
"""
from __future__ import annotations

import numpy as np

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


class CoefficientOfVariation:
    """CV = standard deviation / |mean|, plus the quartile-based robust version."""

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

    def cv(self, values) -> np.ndarray | float:
        """Coefficient of variation.

        values: array-like of any shape; NaN entries are ignored.
        Returns a float when config.axis is None, otherwise an array with that axis removed.
        Where the mean is zero the CV is undefined and the result is NaN.
        """
        x = np.asarray(values, dtype=float)
        axis = self.config.axis
        n = np.sum(~np.isnan(x), axis=axis)
        if np.any(n <= self.config.ddof):
            raise ValueError("not enough values for the chosen ddof")
        mean = np.nanmean(x, axis=axis)
        std = np.nanstd(x, axis=axis, ddof=self.config.ddof)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(mean == 0, np.nan, std / np.abs(mean))
        if self.config.unbiased:
            result = result * (1.0 + 1.0 / (4.0 * n))
        if self.config.as_percent:
            result = result * 100.0
        return float(result) if np.ndim(result) == 0 else result

    def quartile_dispersion(self, values) -> float:
        """Quartile coefficient of dispersion (Q3 - Q1) / (Q3 + Q1): a CV that outliers barely move.

        values: array-like, flattened; NaN entries are ignored.
        """
        x = np.asarray(values, dtype=float).ravel()
        x = x[~np.isnan(x)]
        if x.size == 0:
            raise ValueError("values holds no numbers")
        q1, q3 = np.quantile(x, [0.25, 0.75])
        if q1 + q3 == 0:
            return float("nan")
        result = float((q3 - q1) / (q3 + q1))
        return result * 100.0 if self.config.as_percent else result

    def compare(self, groups: dict) -> list[tuple[str, float]]:
        """CV of every group, most variable first. groups: {label: array-like}. Each group is flattened."""
        flat = CoefficientOfVariation(
            CoefficientOfVariationConfig(self.config.ddof, self.config.as_percent, self.config.unbiased, None)
        )
        scored = [(label, flat.cv(np.asarray(values, dtype=float).ravel())) for label, values in groups.items()]
        return sorted(scored, key=lambda item: -item[1])
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Build CoefficientOfVariation with ddof set to 0 and confirm cv gives 0.4 on the eight values above. Multiply the values by 1000 and check the CV again, then add 100 to every value and check once more. Use compare on two groups of your own and explain the order it returns.

Check on learning

  1. Adding 100 to every value leaves the standard deviation unchanged but changes the CV. Why is that a reason to refuse the CV for temperatures in Celsius?
    A way to think about it

    Switching between Celsius and Kelvin is exactly such a shift. Ask whether a statistic that changes with an arbitrary choice of zero describes the thing measured.

  2. Two machines fill bottles. One has a mean of 500 ml and a standard deviation of 5 ml, the other 50 ml and 2 ml. Which is more consistent, and in what sense?
    A way to think about it

    Compute both CVs. Then ask whether the customer cares about millilitres or about the share of the bottle.

  3. A column of daily profit and loss has a mean close to zero. What does its CV look like from day to day, and what would you report instead?
    A way to think about it

    Watch the denominator. A measure of spread that does not divide by the mean, or the quartile version if the values are positive, avoids the problem.

  4. When would the quartile coefficient of dispersion and the CV rank two groups in opposite order?
    A way to think about it

    Give one group a single extreme value. It moves ss and xˉ\bar{x} but leaves the quartiles almost where they were.