Login
📚 Python for Introductory Statistics
Chapters ▾

14.6 ANOVA (Analysis of Variance)

Watch demo video

One-Way ANOVA

ANOVA (analysis of variance) can be used to test whether the means of more than two groups are statistically different from each other.

Example: The data set below (URL) contains the students test1_score, gender, level, section etc.

  1. Write a program to read the data set and display the first and last five rows.
  2. Write a program to find test1_score means, std and size for each level

my_csv_file.csv

import pandas as pd

url='my_csv_file.csv'

x_df = pd.read_csv(url)

x_df  # print the first and last five rows
idgendersectiontimeleveltest1_scoretest2_scoretest3_score
01femaleC17.3low65.484.351.9
12femaleD5.1low72.486.152.0
23femaleA2.4low73.884.253.1
34femaleA8.8low70.287.952.0
45maleB15.0low60.381.455.5
...........................
175176maleB13.2high78.889.352.5
176177femaleB12.6high76.583.450.0
177178maleD8.4high78.186.351.0
178179maleC9.5high76.686.652.4
179180maleC16.2high83.189.454.1
x_df.groupby(['level']).agg({'test1_score': ['mean', 'std','size']})
test1_score
meanstdsize
level
high79.6133333.61730660
low68.7750004.35028260
medium74.8416673.63888160

Example: The data set below (URL) contains the students test1_score, gender, level, section etc.

my_csv_file.csv

import statsmodels.api as sm
from statsmodels.formula.api import ols
model = ols('test1_score ~ C(level)',data = x_df).fit()
table = sm.stats.anova_lm(model,type=2) # type 2 for equal or non-equal sample sizes
print(table)
Show expected output
             df       sum_sq      mean_sq           F        PR(>F)
C(level)    2.0  3540.854333  1770.427167  117.372972  3.555808e-33
Residual  177.0  2669.827667    15.083772         NaN           NaN

Interpretation: Since the p-value 3.555808e-33 < α = 0.10, reject the null hypothesis that the averages for all three levels are equal. That is, there is a significant difference between the averages of test1_score of the three levels. The sum of squares residual is 2669.827667. The sum of squares treatment (level) is 3540.854333.

Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.