How to Calculate Quartiles and Interquartile Range (IQR) in Python (statistics.quantiles and NumPy)

Let’s see how to calculate quartiles in Python using the statistics.quantiles function for Q1, Q2, and Q3, and NumPy to compute the interquartile range (IQR).

quartiles python

Quartiles calculator

To calculate quartiles, we need to import the statistics module.

Luckily, there is a dedicated function in the statistics module to calculate quartiles.

import statistics as s

x = [1, 5, 7, 5, 43, 43, 8, 43, 6]

quartiles = s.quantiles(x, n=4)
print("Quartiles are: " + str(quartiles))

Interquartile Range (IQR)

To calculate the interquartile range (IQR) in Python, first compute Q1 and Q3 (the 25th and 75th percentiles) and then subtract Q1 from Q3, that is IQR=Q3−Q1.

See also  How to Calculate Mode in Python (statistics.mode, NumPy bincount/argmax, and Examples)

To calculate q1 and q3, you need to calculate the 25th and 75th percentile. You need to use the percentile function for that purpose.

Next, just subtract q3 and q1 to get an iqr in Python.

import statistics as s

import numpy as np

x = [1, 5, 7, 5, 43, 43, 8, 43, 6]

q1 = np.percentile(x, 25)
q3 = np.percentile(x, 75)
iqr = q3 - q1
print("IQR equals: " + str(iqr))

Output:

IQR equals: 38.0