This module provides functions for calculating statistics of data, including
averages, variance, and standard deviation.
================== ==================================================
================== ==================================================
mean Arithmetic mean (average) of data.
fmean Fast, floating point arithmetic mean.
geometric_mean Geometric mean of data.
harmonic_mean Harmonic mean of data.
median Median (middle value) of data.
median_low Low median of data.
median_high High median of data.
median_grouped Median, or 50th percentile, of grouped data.
mode Mode (most common value) of data.
multimode List of modes (most common values of data).
quantiles Divide data into intervals with equal probability.
================== ==================================================
Calculate the arithmetic mean ("the average") of data:
>>> mean([-1.0, 2.5, 3.25, 5.75])
Calculate the standard median of discrete data:
Calculate the median, or 50th percentile, of data grouped into class intervals
centred on the data values provided. E.g. if your data points are rounded to
the nearest whole number:
>>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS
This should be interpreted in this way: you have two data points in the class
interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
the class interval 3.5-4.5. The median of these data points is 2.8333...
Calculating variability or spread
---------------------------------
================== =============================================
================== =============================================
pvariance Population variance of data.
variance Sample variance of data.
pstdev Population standard deviation of data.
stdev Sample standard deviation of data.
================== =============================================
Calculate the standard deviation of sample data:
>>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS
If you have previously calculated the mean, you can pass it as the optional
second argument to the four "spread" functions to avoid recalculating it:
>>> data = [1, 2, 2, 4, 4, 4, 5, 6]
A single exception is defined: StatisticsError is a subclass of ValueError.
from fractions import Fraction
from decimal import Decimal
from itertools import groupby
from bisect import bisect_left, bisect_right
from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum
from operator import itemgetter
from collections import Counter
class StatisticsError(ValueError):
# === Private utilities ===
"""_sum(data [, start]) -> (type, sum, count)
Return a high-precision sum of the given numeric data as a fraction,
together with the type to be converted to and the count of items.
If optional argument ``start`` is given, it is added to the total.
If ``data`` is empty, ``start`` (defaulting to 0) is returned.
>>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
(<class 'float'>, Fraction(11, 1), 5)
Some sources of round-off error will be avoided:
# Built-in sum returns zero.
>>> _sum([1e50, 1, -1e50] * 1000)
(<class 'float'>, Fraction(1000, 1), 3000)
Fractions and Decimals are also supported:
>>> from fractions import Fraction as F
>>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
(<class 'fractions.Fraction'>, Fraction(63, 20), 4)
>>> from decimal import Decimal as D
>>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
(<class 'decimal.Decimal'>, Fraction(6963, 10000), 4)
Mixed types are currently treated as an error, except that int is
n, d = _exact_ratio(start)
partials_get = partials.get
T = _coerce(int, type(start))
for typ, values in groupby(data, type):
T = _coerce(T, typ) # or raise TypeError
for n, d in map(_exact_ratio, values):
partials[d] = partials_get(d, 0) + n
# The sum will be a NAN or INF. We can ignore all the finite
# partials, and just look at this special one.
assert not _isfinite(total)
# Sum all the partial sums using builtin sum.
# FIXME is this faster if we sum them in order of the denominator?
total = sum(Fraction(n, d) for d, n in sorted(partials.items()))
return x.is_finite() # Likely a Decimal.
return math.isfinite(x) # Coerces to float first.
"""Coerce types T and S to a common type, or raise TypeError.
Coercion rules are currently an implementation detail. See the CoerceTest
test class in test_statistics for details.
# See http://bugs.python.org/issue24068.
assert T is not bool, "initial type T is bool"
# If the types are the same, no need to coerce anything. Put this
# first, so that the usual case (no coercion needed) happens as soon
# Mixed int & other coerce to the other type.
if S is int or S is bool: return T
# If one is a (strict) subclass of the other, coerce to the subclass.
if issubclass(S, T): return S
if issubclass(T, S): return T
# Ints coerce to the other type.
if issubclass(T, int): return S
if issubclass(S, int): return T
# Mixed fraction & float coerces to float (or float subclass).
if issubclass(T, Fraction) and issubclass(S, float):
if issubclass(T, float) and issubclass(S, Fraction):
# Any other combination is disallowed.
msg = "don't know how to coerce %s and %s"
raise TypeError(msg % (T.__name__, S.__name__))
"""Return Real number x to exact (numerator, denominator) pair.
x is expected to be an int, Fraction, Decimal or float.
# Optimise the common case of floats. We expect that the most often
# used numeric type will be builtin floats, so try to make this as
if type(x) is float or type(x) is Decimal:
return x.as_integer_ratio()
# x may be an int, Fraction, or Integral ABC.
return (x.numerator, x.denominator)
# x may be a float or Decimal subclass.
return x.as_integer_ratio()
except (OverflowError, ValueError):
msg = "can't convert type '{}' to numerator/denominator"
raise TypeError(msg.format(type(x).__name__))
"""Convert value to given numeric type T."""
# This covers the cases where T is Fraction, or where value is
# a NAN or INF (Decimal or float).
if issubclass(T, int) and value.denominator != 1:
# FIXME: what do we do if this overflows?
if issubclass(T, Decimal):
return T(value.numerator) / T(value.denominator)
'Locate the leftmost value exactly equal to x'
if i != len(a) and a[i] == x:
'Locate the rightmost value exactly equal to x'
i = bisect_right(a, x, lo=l)
if i != (len(a) + 1) and a[i - 1] == x:
def _fail_neg(values, errmsg='negative value'):
"""Iterate over values, failing if any are less than zero."""
raise StatisticsError(errmsg)
# === Measures of central tendency (averages) ===
"""Return the sample arithmetic mean of data.
>>> mean([1, 2, 3, 4, 4])
>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
If ``data`` is empty, StatisticsError will be raised.
raise StatisticsError('mean requires at least one data point')
T, total, count = _sum(data)
return _convert(total / n, T)
"""Convert data to floats and compute the arithmetic mean.
This runs faster than the mean() function and it always returns a float.
If the input dataset is empty, it raises a StatisticsError.
>>> fmean([3.5, 4.0, 5.25])
# Handle iterators that do not define __len__().
for n, x in enumerate(iterable, start=1):
total = fsum(count(data))
except ZeroDivisionError:
raise StatisticsError('fmean requires at least one data point') from None
def geometric_mean(data):
"""Convert data to floats and compute the geometric mean.
Raises a StatisticsError if the input dataset is empty,
if it contains a zero, or if it contains a negative value.
No special efforts are made to achieve exact results.
(However, this may change in the future.)
>>> round(geometric_mean([54, 24, 36]), 9)
return exp(fmean(map(log, data)))
raise StatisticsError('geometric mean requires a non-empty dataset '
' containing positive numbers') from None
"""Return the harmonic mean of data.
The harmonic mean, sometimes called the subcontrary mean, is the
reciprocal of the arithmetic mean of the reciprocals of the data,
and is often appropriate when averaging quantities which are rates
or ratios, for example speeds. Example:
Suppose an investor purchases an equal value of shares in each of
three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
What is the average P/E ratio for the investor's portfolio?
>>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
Using the arithmetic mean would give an average of about 5.167, which
If ``data`` is empty, or any element is less than zero,
``harmonic_mean`` will raise ``StatisticsError``.
# For a justification for using harmonic mean for P/E ratios, see
# http://fixthepitch.pellucid.com/comps-analysis-the-missing-harmony-of-summary-statistics/
# http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2621087
errmsg = 'harmonic mean does not support negative values'
raise StatisticsError('harmonic_mean requires at least one data point')
if isinstance(x, (numbers.Real, Decimal)):
raise StatisticsError(errmsg)
raise TypeError('unsupported type')
T, total, count = _sum(1 / x for x in _fail_neg(data, errmsg))
except ZeroDivisionError:
return _convert(n / total, T)
# FIXME: investigate ways to calculate medians without sorting? Quickselect?
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
raise StatisticsError("no median for empty data")
return (data[i - 1] + data[i]) / 2
"""Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.
>>> median_low([1, 3, 5])
>>> median_low([1, 3, 5, 7])
raise StatisticsError("no median for empty data")
"""Return the high median of data.
When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned.
>>> median_high([1, 3, 5])
>>> median_high([1, 3, 5, 7])
raise StatisticsError("no median for empty data")
def median_grouped(data, interval=1):
"""Return the 50th percentile (median) of grouped continuous data.
>>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
>>> median_grouped([52, 52, 53, 54])
This calculates the median as the 50th percentile, and should be
used when your data is continuous and grouped. In the above example,
the values 1, 2, 3, etc. actually represent the midpoint of classes
0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
class 3.5-4.5, and interpolation is used to estimate it.
Optional argument ``interval`` represents the class interval, and
defaults to 1. Changing the class interval naturally will change the
interpolated 50th percentile value:
>>> median_grouped([1, 3, 3, 5, 7], interval=1)
>>> median_grouped([1, 3, 3, 5, 7], interval=2)