Calculate the Interquartile Range in Python

Your goal

You need to calculate the interquartile range (IQR) of a numerical dataset in Python.

Step-by-step tutorial

You can use scipy.stats.iqr for this.

>>> from scipy import stats

We'll show how to calculate the IQR for both list data and a Series in a Pandas DataFrame.

Approach 1: List data

>>> stats.iqr([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9])
4.5

Approach 2: Pandas DataFrame Series

>>> import pandas as pd
>>> precip = pd.read_csv('precip-central-park.csv')
>>> stats.iqr(precip['JUL'])
2.84