typestar

ANOVA tables in Python

anova_lm turns a fitted model into a sum-of-squares table.

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from statsmodels.stats.anova import anova_lm

rng = np.random.default_rng(10)
frame = pd.DataFrame({
    "lang": np.tile(["python", "rust", "sql"], 40),
    "editor": np.repeat([0, 1], 60),
})
frame["tpm"] = (90 + frame["lang"].map({"python": 8.0, "rust": 4.0,
                                        "sql": 0.0})
                + 5 * frame["editor"] + rng.normal(0, 4, size=120))

full = smf.ols("tpm ~ C(lang) + editor", data=frame).fit()
print(anova_lm(full, typ=2).round(4))

reduced = smf.ols("tpm ~ editor", data=frame).fit()
print(full.compare_f_test(reduced)[:2])

How it works

  1. typ=2 is the usual choice for unbalanced designs.
  2. Each row is a term, with its F and p.
  3. Comparing two nested models is a different call: compare_f_test.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
585
Tokens
212
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 116 seconds.

Type this snippet

Step 3 of 4 in Beyond least squares, step 11 of 19 in Statistics with statsmodels.

← Previous Next →