
Introduction
Quantiles is a fundamental concept in statistics that divides a dataset into equal-sized intervals. In Python, the statistics module provides a straightforward way to calculate quantiles through the quantiles() function.
In this article, we look at the usage of the quantiles() function, providing examples and explanations to facilitate understanding.
Using the statistics.quantiles() Function
Before using the quantiles() function, you need to import the statistics module.
import statistics
The syntax for the quantiles() function is as follows:
statistics.quantiles(data, n=4, method='exclusive')
The quantiles() function in Python’s statistics module takes the following parameters:
- data: A list of numbers from which quantiles are calculated
- n: The number of quantiles to compute (default is 4, which corresponds to quartiles)
- method: Determines the type of quantile calculation (‘exclusive’ or ‘inclusive’)
The method defines whether or not the data includes the lowest and highest possible values from the population. The default method is exclusive.
To illustrate basic usage, let’s calculate the quartiles of our example dataset:
import statistics data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] quartiles = statistics.quantiles(data) print(quartiles) # Output: [2.75, 5.5, 8.25]
In this example, the function returns three values: the first quartile (Q1), the second quartile (Q2), and the third quartile (Q3).
The n parameter allows you to specify different types of quantiles. For instance, if you set n=10, you can calculate deciles, which divide the data into ten equal parts. Here’s how to calculate deciles:
deciles = statistics.quantiles(data, n=10) print(deciles) # Output: [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]
In this case, the function returns the values that separate the lowest 10% of the data from the next 10%, and so on.
The method parameter in the quantiles() function allows you to choose between two types of quantile calculations: ‘exclusive’ and ‘inclusive’.
- Exclusive: This method calculates quantiles by excluding the endpoints of the dataset
- Inclusive: This method includes the endpoints in the calculation
Here’s an example comparing both methods:
import statistics data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] inclusive_quartiles = statistics.quantiles(data, method='inclusive') exclusive_quartiles = statistics.quantiles(data, method='exclusive') print(inclusive_quartiles) print(exclusive_quartiles) # Output: # [3.25, 5.5, 7.75] # [2.75, 5.5, 8.25]
Calling quantiles() on an empty list will raise a StatisticsError. Here’s an example:
empty_data = []
try:
quantiles_empty = statistics.quantiles(empty_data)
except StatisticsError as e:
print(e)
# Output: no data
Wrapping Up
In this article, we looked at the statistics.quantiles() function, and discussed its purpose and usage. You can see its official documentation for more information.
