statistics --- 数学统计函数

3.4 新版功能.

源代码: Lib/statistics.py


该模块提供了用于计算数字 (Real 值) 数据的数理统计量的函数。

注解

除非明确注释,这些函数支持 int, float, decimal.Decimalfractions.Fraction。 当前不支持同其他类型(不论是否在数字塔中)的行为。 混合类型也是未定义且取决于具体实现的。 如果你输入由混合类型组成的数据,你应该能够使用 map() 来确保得到一致的结果,例如 map(float, input_data)

平均值以及对中心位置的评估

这些函数用于计算一个总体或样本的平均值或者典型值。

mean()

数据的算术平均数(“平均数”)。

harmonic_mean()

数据的调和均值

median()

数据的中位数(中间值)

median_low()

数据的低中位数

median_high()

数据的高中位数

median_grouped()

分组数据的中位数,即第50个百分点。

mode()

Mode (most common value) of discrete data.

对分散程度的评估

这些函数用于计算总体或样本与典型值或平均值的偏离程度。

pstdev()

数据的总体标准差

pvariance()

数据的总体方差

stdev()

数据的样本标准差

variance()

数据的样本方差

函数细节

注释:这些函数不需要对提供给它们的数据进行排序。但是,为了方便阅读,大多数例子展示的是已排序的序列。

statistics.mean(data)

返回 data 的样本算术平均数,数据可是是一个序列或迭代器。

算术平均数是数据之和与数据点个数的商。通常称作“平均数”,尽管它指示诸多数学平均数之一。它是数据中心位置的度量。

data 为空,将会引发 StatisticsError

一些用法示例:

>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625

>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)

>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')

注解

The mean is strongly affected by outliers and is not a robust estimator for central location: the mean is not necessarily a typical example of the data points. For more robust, although less efficient, measures of central location, see median() and mode(). (In this case, "efficient" refers to statistical efficiency rather than computational efficiency.)

The sample mean gives an unbiased estimate of the true population mean, which means that, taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ.

statistics.harmonic_mean(data)

返回 data 的调和均值,数据可以是序列或实数值的迭代器。

调和均值,也叫次相反均值,所有数据的倒数的算术平均数 mean() 的倒数。比如说,数据 abc 的调和均值等于 3/(1/a + 1/b + 1/c)

The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging quantities which are rates or ratios, for example speeds. For example:

假设一名投资者在三家公司各购买了等价值的股票,以 2.5, 3 , 10 的 P/E (投资/回报) 率。投资者投资组合的平均市盈率是多少?

>>> harmonic_mean([2.5, 3, 10])  # For an equal investment portfolio.
3.6

Using the arithmetic mean would give an average of about 5.167, which is too high.

如果 data 为空或者 任何一个元素的值小于零,会引发 StatisticsError

3.6 新版功能.

statistics.median(data)

使用常见的“取中间两数平均值”方法,返回数字数据的中位数(中间值)。如果 data 为空,则引发 StatisticsErrordata  可以是序列或迭代器。

The median is a robust measure of central location, and is less affected by the presence of outliers in your data. When the number of data points is odd, the middle data point is returned:

>>> median([1, 3, 5])
3

当数据点的总数为偶数时,中位数将通过对两个中间值求平均进行插值得出:

>>> median([1, 3, 5, 7])
4.0

这适用于当你的数据是离散的,并且你不介意中位数不是实际数据点的情况。

If your data is ordinal (supports order operations) but not numeric (doesn't support addition), you should use median_low() or median_high() instead.

statistics.median_low(data)

Return the low median of numeric data. If data is empty, StatisticsError is raised. data can be a sequence or iterator.

低中位数一定是数据集的成员。 当数据点总数为奇数时,将返回中间值。 当其为偶数时,将返回两个中间值中较小的那个。

>>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3

当你的数据是离散的,并且你希望中位数是一个实际数据点而非插值结果时可以使用低中位数。

statistics.median_high(data)

Return the high median of data. If data is empty, StatisticsError is raised. data can be a sequence or iterator.

高中位数一定是数据集的成员。 当数据点总数为奇数时,将返回中间值。 当其为偶数时,将返回两个中间值中较大的那个。

>>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5

当你的数据是离散的,并且你希望中位数是一个实际数据点而非插值结果时可以使用高中位数。

statistics.median_grouped(data, interval=1)

Return the median of grouped continuous data, calculated as the 50th percentile, using interpolation. If data is empty, StatisticsError is raised. data can be a sequence or iterator.

>>> median_grouped([52, 52, 53, 54])
52.5

在下面的示例中,数据已经过舍入,这样每个值都代表数据分类的中间点,例如 1 是 0.5--1.5 分类的中间点,2 是 1.5--2.5 分类的中间点,3 是 2.5--3.5 的中间点等待。 根据给定的数据,中间值应落在 3.5--4.5 分类之内,并可使用插值法来进行估算:

>>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
3.7

可选参数 interval 表示分类间隔,默认值为 1。 改变分类间隔自然会改变插件结果:

>>> median_grouped([1, 3, 3, 5, 7], interval=1)
3.25
>>> median_grouped([1, 3, 3, 5, 7], interval=2)
3.5

此函数不会检查数据点之间是否至少相隔 interval 的距离。

CPython implementation detail: 在某些情况下,median_grouped() 可以会将数据点强制转换为浮点数。 此行为在未来有可能会发生改变。

参见

  • "Statistics for the Behavioral Sciences", Frederick J Gravetter and Larry B Wallnau (8th Edition).

  • Gnome Gnumeric 电子表格中的 SSMEDIAN 函数,包括 这篇讨论

statistics.mode(data)

Return the most common data point from discrete or nominal data. The mode (when it exists) is the most typical value, and is a robust measure of central location.

If data is empty, or if there is not exactly one most common value, StatisticsError is raised.

mode assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools:

>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3

The mode is unique in that it is the only statistic which also applies to nominal (non-numeric) data:

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
statistics.pstdev(data, mu=None)

返回总体标准差(总体方差的平方根)。 请参阅 pvariance() 了解参数和其他细节。

>>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251
statistics.pvariance(data, mu=None)

Return the population variance of data, a non-empty iterable of real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.

If the optional second argument mu is given, it should be the mean of data. If it is missing or None (the default), the mean is automatically calculated.

使用此函数可根据所有数值来计算方差。 要根据一个样本来估算方差,通常 variance() 函数是更好的选择。

如果 data 为空则会引发 StatisticsError

示例:

>>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25

如果你已经计算过数据的平均值,你可以将其作为可选的第二个参数 mu 传入以避免重复计算:

>>> mu = mean(data)
>>> pvariance(data, mu)
1.25

This function does not attempt to verify that you have passed the actual mean as mu. Using arbitrary values for mu may lead to invalid or impossible results.

同样也支持使用 Decimal 和 Fraction 值:

>>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')

>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)

注解

当调用时附带完整的总体数据时,这将给出总体方差 σ²。 而当调用时只附带一个样本时,这将给出偏置样本方差 s²,也被称为带有 N 个自由度的方差。

If you somehow know the true population mean μ, you may use this function to calculate the variance of a sample, giving the known population mean as the second argument. Provided the data points are representative (e.g. independent and identically distributed), the result will be an unbiased estimate of the population variance.

statistics.stdev(data, xbar=None)

返回样本标准差(样本方差的平方根)。 请参阅 variance() 了解参数和其他细节。

>>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827
statistics.variance(data, xbar=None)

返回包含至少两个实数值的可迭代对象 data 的样本方差。 方差或称相对于均值的二阶矩,是对数据变化幅度(延展度或分散度)的度量。 方差值较大表明数据的散布范围较大;方差值较小表明它紧密聚集于均值附近。

如果给出了可选的第二个参数 xbar,它应当是 data 的均值。 如果该参数省略或为 None (默认值),则会自动进行均值的计算。

当你的数据是总体数据的样本时请使用此函数。 要根据整个总体数据来计算方差,请参见 pvariance()

如果 data 包含的值少于两个则会引发 StatisticsError

示例:

>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095

如果你已经计算过数据的平均值,你可以将其作为可选的第二个参数 xbar 传入以避免重复计算:

>>> m = mean(data)
>>> variance(data, m)
1.3720238095238095

此函数不会试图检查你所传入的 xbar 是否为真实的平均值。 使用任意值作为 xbar 可能导致无效或不可能的结果。

同样也支持使用 Decimal 和 Fraction 值:

>>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')

>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)

注解

这是附带贝塞尔校正的样本方差 s²,也称为具有 N-1 自由度的方差。 假设数据点具有代表性(即为独立且均匀的分布),则结果应当是对总体方差的无偏估计。

如果你通过某种方式知道了真实的总体平均值 μ 则应当调用 pvariance() 函数并将该值作为 mu 形参传入以得到一个样本的方差。

异常

只定义了一个异常:

exception statistics.StatisticsError

ValueError 的子类,表示统计相关的异常。