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
y ~ x1 + x2names the response and the predictors.- The intercept is included unless you subtract it.
- The data argument is a DataFrame, and columns are looked up by name.
Keywords and builtins used here
asprintround
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.
Step 2 of 3 in Linear models, step 2 of 19 in Statistics with statsmodels.