9.7.statistics — Mathematical statistics functions

New in version 3.4.

Source code:Lib/statistics.py


This module provides functions for calculating mathematical statistics ofnumeric (Real-valued) data.

Note

Unless explicitly noted otherwise, these functions supportint,float,decimal.Decimal andfractions.Fraction.Behaviour with other types (whether in the numeric tower or not) iscurrently unsupported. Mixed types are also undefined andimplementation-dependent. If your input data consists of mixed types,you may be able to usemap() to ensure a consistent result, e.g.map(float,input_data).

9.7.1.Averages and measures of central location

These functions calculate an average or typical value from a populationor sample.

mean()

Arithmetic mean (“average”) 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 discrete data.

9.7.2.Measures of spread

These functions calculate a measure of how much the population or sampletends to deviate from the typical or average values.

pstdev()

Population standard deviation of data.

pvariance()

Population variance of data.

stdev()

Sample standard deviation of data.

variance()

Sample variance of data.

9.7.3.Function details

Note: The functions do not require the data given to them to be sorted.However, for reading convenience, most of the examples show sorted sequences.

statistics.mean(data)

Return the sample arithmetic mean ofdata which can be a sequence or iterator.

The arithmetic mean is the sum of the data divided by the number of datapoints. It is commonly called “the average”, although it is only one of manydifferent mathematical averages. It is a measure of the central location ofthe data.

Ifdata is empty,StatisticsError will be raised.

Some examples of use:

>>>mean([1,2,3,4,4])2.8>>>mean([-1.0,2.5,3.25,5.75])2.625>>>fromfractionsimportFractionasF>>>mean([F(3,7),F(1,21),F(5,3),F(1,3)])Fraction(13, 21)>>>fromdecimalimportDecimalasD>>>mean([D("0.5"),D("0.75"),D("0.625"),D("0.375")])Decimal('0.5625')

Note

The mean is strongly affected by outliers and is not a robust estimatorfor central location: the mean is not necessarily a typical example of thedata points. For more robust, although less efficient, measures ofcentral location, seemedian() andmode(). (In this case,“efficient” refers to statistical efficiency rather than computationalefficiency.)

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. Ifdata represents the entire population rather than a sample, thenmean(data) is equivalent to calculating the true population mean μ.

statistics.harmonic_mean(data)

Return the harmonic mean ofdata, a sequence or iterator ofreal-valued numbers.

The harmonic mean, sometimes called the subcontrary mean, is thereciprocal of the arithmeticmean() of the reciprocals of thedata. For example, the harmonic mean of three valuesa,b andcwill be equivalent to3/(1/a+1/b+1/c).

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

Suppose an investor purchases an equal value of shares in each ofthree 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.3.6

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

StatisticsError is raised ifdata is empty, or any elementis less than zero.

New in version 3.6.

statistics.median(data)

Return the median (middle value) of numeric data, using the common “mean ofmiddle two” method. Ifdata is empty,StatisticsError is raised.data can be a sequence or iterator.

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

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

When the number of data points is even, the median is interpolated by takingthe average of the two middle values:

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

This is suited for when your data is discrete, and you don’t mind that themedian may not be an actual data point.

If your data is ordinal (supports order operations) but not numeric (doesn’tsupport addition), you should usemedian_low() ormedian_high()instead.

statistics.median_low(data)

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

The low median is always a member of the data set. When the number of datapoints is odd, the middle value is returned. When it is even, the smaller ofthe two middle values is returned.

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

Use the low median when your data are discrete and you prefer the median tobe an actual data point rather than interpolated.

statistics.median_high(data)

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

The high median is always a member of the data set. When the number of datapoints is odd, the middle value is returned. When it is even, the larger ofthe two middle values is returned.

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

Use the high median when your data are discrete and you prefer the median tobe an actual data point rather than interpolated.

statistics.median_grouped(data,interval=1)

Return the median of grouped continuous data, calculated as the 50thpercentile, using interpolation. Ifdata is empty,StatisticsErroris raised.data can be a sequence or iterator.

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

In the following example, the data are rounded, so that each value representsthe midpoint of data classes, e.g. 1 is the midpoint of the class 0.5–1.5, 2is the midpoint of 1.5–2.5, 3 is the midpoint of 2.5–3.5, etc. With the datagiven, the middle value falls somewhere in the class 3.5–4.5, andinterpolation is used to estimate it:

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

Optional argumentinterval represents the class interval, and defaultsto 1. Changing the class interval naturally will change the interpolation:

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

This function does not check whether the data points are at leastinterval apart.

CPython implementation detail: Under some circumstances,median_grouped() may coerce data points tofloats. This behaviour is likely to change in the future.

See also

  • “Statistics for the Behavioral Sciences”, Frederick J Gravetter andLarry B Wallnau (8th Edition).

  • Calculating themedian.

  • TheSSMEDIANfunction in the Gnome Gnumeric spreadsheet, includingthis discussion.

statistics.mode(data)

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

Ifdata 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 thestandard 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 appliesto nominal (non-numeric) data:

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

Return the population standard deviation (the square root of the populationvariance). Seepvariance() for arguments and other details.

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

Return the population variance ofdata, a non-empty iterable of real-valuednumbers. Variance, or second moment about the mean, is a measure of thevariability (spread or dispersion) of data. A large variance indicates thatthe data is spread out; a small variance indicates it is clustered closelyaround the mean.

If the optional second argumentmu is given, it should be the mean ofdata. If it is missing orNone (the default), the mean isautomatically calculated.

Use this function to calculate the variance from the entire population. Toestimate the variance from a sample, thevariance() function is usuallya better choice.

RaisesStatisticsError ifdata is empty.

Examples:

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

If you have already calculated the mean of your data, you can pass it as theoptional second argumentmu to avoid recalculation:

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

This function does not attempt to verify that you have passed the actual meanasmu. Using arbitrary values formu may lead to invalid or impossibleresults.

Decimals and Fractions are supported:

>>>fromdecimalimportDecimalasD>>>pvariance([D("27.5"),D("30.25"),D("30.25"),D("34.5"),D("41.75")])Decimal('24.815')>>>fromfractionsimportFractionasF>>>pvariance([F(1,4),F(5,4),F(1,2)])Fraction(13, 72)

Note

When called with the entire population, this gives the population varianceσ². When called on a sample instead, this is the biased sample variances², also known as variance with N degrees of freedom.

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

statistics.stdev(data,xbar=None)

Return the sample standard deviation (the square root of the samplevariance). Seevariance() for arguments and other details.

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

Return the sample variance ofdata, an iterable of at least two real-valuednumbers. Variance, or second moment about the mean, is a measure of thevariability (spread or dispersion) of data. A large variance indicates thatthe data is spread out; a small variance indicates it is clustered closelyaround the mean.

If the optional second argumentxbar is given, it should be the mean ofdata. If it is missing orNone (the default), the mean isautomatically calculated.

Use this function when your data is a sample from a population. To calculatethe variance from the entire population, seepvariance().

RaisesStatisticsError ifdata has fewer than two values.

Examples:

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

If you have already calculated the mean of your data, you can pass it as theoptional second argumentxbar to avoid recalculation:

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

This function does not attempt to verify that you have passed the actual meanasxbar. Using arbitrary values forxbar can lead to invalid orimpossible results.

Decimal and Fraction values are supported:

>>>fromdecimalimportDecimalasD>>>variance([D("27.5"),D("30.25"),D("30.25"),D("34.5"),D("41.75")])Decimal('31.01875')>>>fromfractionsimportFractionasF>>>variance([F(1,6),F(1,2),F(5,3)])Fraction(67, 108)

Note

This is the sample variance s² with Bessel’s correction, also known asvariance with N-1 degrees of freedom. Provided that the data points arerepresentative (e.g. independent and identically distributed), the resultshould be an unbiased estimate of the true population variance.

If you somehow know the actual population mean μ you should pass it to thepvariance() function as themu parameter to get the variance of asample.

9.7.4.Exceptions

A single exception is defined:

exceptionstatistics.StatisticsError

Subclass ofValueError for statistics-related exceptions.