Let’s see how to calculate quartiles in Python.
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, just subtract q3 from q1 values.
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))
IQR equals: 38.0