Python statistics.quantiles() Function



The Python statistics.quantiles() function divides data into 'n' continuous intervals with equal probability. Each probability returns a list of 'n-1' intervals.

The function for computing quantiles can be varied depending on whether the data includes or excludes the lowest and highest possible values from the population. The data can be iterable sample data, the number of data points in the data should be greater than n. This function throws a StaticError if there are no two data points.

In this function, the default value is "exclusive," and this is used for data sampling from a population that can have more extreme values i.e., those found in the samples.

Whereas "inclusive" is used for describing population data or for samples that are known to include the most common extreme values, from the population. The minimum value in the data is treated as the 0th percentile, and the maximum value is treated as the 100th percentile.

Syntax

Following is the basic syntax for the statistics.quantiles() function −

statistics.quantiles(data, *, n=4, method='exclusive')

Parameters

Here, the data and weight values can be used as any sequence, list or iterator from the exclusive function.

Return Value

This function returns a list of n-1 cut points separating the intervals.

Example 1

In the below example, we are calculating the decile cut points for empirically sampled data using statistics.quantiles() function.

data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
        100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
        106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
        111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
        103, 107, 101, 81, 109, 104]
import statistics
quantiles = statistics.quantiles(data)
print(quantiles)

Output

The output is obtained as follows −

[87.0, 102.5, 108.25]

Example 2

Now that we are calculating only one data point, this returns a StaticError.

data = ["welcome to tutorials point"]
import statistics
quantiles = statistics.quantiles(data)
print(quantiles)

Output

The result is produced as follows −

Traceback (most recent call last):
  File "/home/cg/root/48234/main.py", line 3, in <module>
    quantiles = statistics.quantiles(data)
  File "/usr/lib/python3.10/statistics.py", line 662, in quantiles
    raise StatisticsError('must have at least two data points')
statistics.StatisticsError: must have at least two data points

Example 3

Here, we are calculating the basic program using statistics.quantiles() function.

data = [2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 2, 2, 2, 3, 3, 3, 4, 4, 2]
import statistics
quantiles = statistics.quantiles(data)
print(quantiles)

Output

We will get the following output as follows −

[2.0, 3.0, 5.0]
python_modules.htm
Advertisements