To calculate the IQR (Interquartile Range) in Pandas, you can use the quantile() function to compute the 25th percentile (Q1) and the 75th percentile (Q3) and then subtract Q1 from Q3.
Here’s an example code:
import pandas as pd # create a sample dataframe data = {'score': [3, 8, 12, 16, 20, 25, 27, 30, 35, 40, 45]} df = pd.DataFrame(data) # calculate the IQR Q1 = df['score'].quantile(0.25) Q3 = df['score'].quantile(0.75) IQR = Q3 - Q1 print("Q1:", Q1) print("Q3:", Q3) print("IQR:", IQR)
Output:
Q1: 13.0 Q3: 33.75 IQR: 20.75
In this example, we created a DataFrame with a column named ‘score’ and calculated the IQR of the values in that column. The quantile() function is used to compute the 25th and 75th percentiles, and then the IQR is calculated as the difference between them.