typestar

The formula API in Python

A patsy formula reads like the model you would write on paper.

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(1)
frame = pd.DataFrame({
    "practice": np.arange(1, 81),
    "hours": rng.uniform(0.5, 3.0, size=80),
})
frame["tpm"] = (70 + 0.6 * frame["practice"] + 4 * frame["hours"]
                + rng.normal(0, 3, size=80))

model = smf.ols("tpm ~ practice + hours", data=frame).fit()
print(model.params.round(3).to_dict())
print(round(model.fvalue, 2), f"{model.f_pvalue:.2e}")
print(model.summary().tables[0].data[0])

How it works

  1. y ~ x1 + x2 names the response and the predictors.
  2. The intercept is included unless you subtract it.
  3. The data argument is a DataFrame, and columns are looked up by name.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
496
Tokens
179
Three-star pace
105 tpm

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

Type this snippet

Step 2 of 3 in Linear models, step 2 of 19 in Statistics with statsmodels.

← Previous Next →