Text of docs.python.org › 3.15 › library › statistics.html as Styx crawled it on Nov 20, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

statistics — Mathematical statistics functions — Python 3.15.2 documentation

Navigation index modules | next | previous | Python » 3.15.2 documentation » The Python standard library » Numeric and Mathematical Modules » statistics — Mathematical statistics functions | Theme | statistics — Mathematical statistics functions ¶ Added in version 3.4. Source code: Lib/statistics.py This module provides functions for calculating mathematical statistics of numeric ( Real -valued) data. The module is not intended to be a competitor to third-party libraries such as NumPy , SciPy , or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab.

It is aimed at the level of graphing and scientific calculators. Unless explicitly noted, these functions support int , float , Decimal and Fraction . Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Collections with a mix of types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, for example: map(float, input_data) .

Some datasets use NaN (not a number) values to represent missing data. Since NaNs have unusual comparison semantics, they cause surprising or undefined behaviors in the statistics functions that sort data or that count occurrences. The functions affected are median() , median_low() , median_high() , median_grouped() , mode() , multimode() , and quantiles() . The NaN values should be stripped before calling these functions: >>> from statistics import median >>> from math import isnan >>> from itertools import filterfalse >>> data = [ 20.7 , float ( 'NaN' ), 19.2 , 18.3 , float ( 'NaN' ), 14.4 ] >>> sorted ( data ) # This has surprising behavior [20.7, nan, 14.4, 18.3, 19.2, nan] >>> median ( data ) # This result is unexpected 16.35 >>> sum ( map ( isnan , data )) # Number of missing values 2 >>> clean = list ( filterfalse ( isnan , data )) # Strip NaN values >>> clean [20.7, 19.2, 18.3, 14.4] >>> sorted ( clean ) # Sorting now works as expected [14.4, 18.3, 19.2, 20.7] >>> median ( clean ) # This result is now well defined 18.75 Averages and measures of central location ¶ These functions calculate an average or typical value from a population or sample. mean() Arithmetic mean (“average”) of data. fmean() Fast, floating-point arithmetic mean, with optional weighting. geometric_mean() Geometric mean of data. harmonic_mean() Harmonic mean of data. kde() Estimate the probability density distribution of the data. kde_random() Random sampling from the PDF generated by kde(). median() Median (middle value) of data. median_low() Low median of data. median_high() High median of data. median_grouped() Median (50th percentile) of grouped data. mode() Single mode (most common value) of discrete or nominal data. multimode() List of modes (most common values) of discrete or nominal data. quantiles() Divide data into intervals with equal probability.

Measures of spread ¶ These functions calculate a measure of how much the population or sample tends 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. Statistics for relations between two inputs ¶ These functions calculate statistics regarding relations between two inputs. covariance() Sample covariance for two variables. correlation() Pearson and Spearman’s correlation coefficients. linear_regression() Slope and intercept for simple linear regression.

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 of data which can be a sequence or iterable. The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages.

It is a measure of the central location of the data. If data 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 >>> 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') Note The mean is strongly affected by outliers and is not necessarily a typical example of the data points.

For a more robust, although less efficient, measure of central tendency , see median() . The sample mean gives an unbiased estimate of the true population mean, so that when 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. fmean ( data , weights = None ) ¶ Convert data to floats and compute the arithmetic mean.

This runs faster than the mean() function and it always returns a float . The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError . >>> fmean ([ 3.5 , 4.0 , 5.25 ]) 4.25 Optional weighting is supported. For example, a professor assigns a grade for a course by weighting quizzes at 20%, homework at 20%, a midterm exam at 30%, and a final exam at 30%: >>> grades = [ 85 , 92 , 83 , 91 ] >>> weights = [ 0.20 , 0.20 , 0.30 , 0.30 ] >>> fmean ( grades , weights ) 87.6 If weights is supplied, it must be the same length as the data or a ValueError will be raised.

Added in version 3.8. Changed in version 3.11: Added support for weights . statistics. geometric_mean ( data ) ¶ Convert data to floats and compute the geometric mean. The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum). Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value.

The data may be a sequence or iterable. No special efforts are made to achieve exact results. (However, this may change in the future.) >>> round ( geometric_mean ([ 54 , 24 , 36 ]), 1 ) 36.0 Added in version 3.8. statistics. harmonic_mean ( data , weights = None ) ¶ Return the harmonic mean of data , a sequence or iterable of real-valued numbers. If weights is omitted or None , then equal weighting is assumed. The harmonic mean is the reciprocal of the arithmetic mean() of the reciprocals of the data.

For example, the harmonic mean of three values a , b and c will be equivalent to 3/(1/a + 1/b + 1/c) . If one of the values is zero, the result will be zero. The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging ratios or rates, for example speeds. Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. What is the average speed? >>> harmonic_mean ([ 40 , 60 ]) 48.0 Suppose a car travels 40 km/hr for 5 km, and when traffic clears, speeds-up to 60 km/hr for the remaining 30 km of the journey.

What is the average speed? >>> harmonic_mean ([ 40 , 60 ], weights = [ 5 , 30 ]) 56.0 StatisticsError is raised if data is empty, any element is less than zero, or if the weighted sum isn’t positive. The current algorithm has an early-out when it encounters a zero in the input. This means that the subsequent inputs are not tested for validity. (This behavior may change in the future.) Added in version 3.6. Changed in version 3.10: Added support for weights . statistics. kde ( data , h , kernel = 'normal' , * , cumulative = False ) ¶ Kernel Density Estimation (KDE) : Create a continuous probability density function or cumulative distribution function from discrete samples.

The basic idea is to

The rest of this page is on the live site.