DS Regression Table
After fitting a model, statsmodels can print a complete regression table with model.summary(). It looks intimidating at first, but it has only three parts, and the next lessons walk through each of them.
Here is the table for rides ~ temp_c on the Riverside Bikes data:
OLS Regression Results
==============================================================================
Dep. Variable: rides R-squared: 0.726
Model: OLS Adj. R-squared: 0.721
Method: Least Squares F-statistic: 153.6
Date: (date of the run) Prob (F-statistic): 6.10e-18
Time: (time of the run) Log-Likelihood: -327.05
No. Observations: 60 AIC: 658.1
Df Residuals: 58 BIC: 662.3
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 135.8133 19.205 7.072 0.000 97.371 174.255
temp_c 12.5449 1.012 12.393 0.000 10.519 14.571
==============================================================================
Omnibus: 2.054 Durbin-Watson: 1.422
Prob(Omnibus): 0.358 Jarque-Bera (JB): 1.257
Skew: -0.255 Prob(JB): 0.534
Kurtosis: 3.492 Cond. No. 49.3
==============================================================================Note: The real
summary()prints the current date and time, and is wider than this page, so the playgrounds in this course print selected parts of it instead. Tryprint(model.summary())yourself in any playground — it works, it's just long.
The three parts
| Part | Contains | Lesson |
|---|---|---|
| Top: model information | What was fitted, how many observations, overall fit (R², F-statistic, AIC) | Regression Info, R-Squared |
| Middle: coefficient table | One row per term: estimate, standard error, t, p-value, 95 % confidence interval | Coefficients, P-Value |
| Bottom: residual diagnostics | Tests of the residuals' shape and independence | Residual Analysis |
Every number is an attribute
Everything in the table is also available as an attribute of the results object, which is how you use the numbers in code:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
model = smf.ols("rides ~ temp_c", data=bikes).fit()
print("observations:", int(model.nobs))
print("R-squared: ", round(model.rsquared, 3))
print("coefficients:", model.params.round(4).to_dict())
print("std errors: ", model.bse.round(3).to_dict())
print("t values: ", model.tvalues.round(3).to_dict())
print("p values: ", {k: f"{v:.2e}" for k, v in model.pvalues.items()})observations: 60
R-squared: 0.726
coefficients: {'Intercept': 135.8133, 'temp_c': 12.5449}
std errors: {'Intercept': 19.205, 'temp_c': 1.012}
t values: {'Intercept': 7.072, 'temp_c': 12.393}
p values: {'Intercept': '2.22e-09', 'temp_c': '6.10e-18'}
The p-values are so tiny (10⁻⁹ and 10⁻¹⁸) that the summary rounds them to 0.000.
The coefficient table as a DataFrame
model.summary2() returns the same information as a list of pandas tables. Table [1] is the coefficient table — a DataFrame you can round, filter or export:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
model = smf.ols("rides ~ temp_c", data=bikes).fit()
coef_table = model.summary2().tables[1]
print(coef_table.round(3))
print()
print(type(coef_table).__name__, coef_table.shape) Coef. Std.Err. t P>|t| [0.025 0.975]
Intercept 135.813 19.205 7.072 0.0 97.371 174.255
temp_c 12.545 1.012 12.393 0.0 10.519 14.571
DataFrame (2, 6)
A compact, reusable report
In practice you'll often write a small helper that prints just what you need. This one is reused in later lessons:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
def report(model):
print(f"{model.model.formula} n={int(model.nobs)} "
f"R2={model.rsquared:.3f} adj R2={model.rsquared_adj:.3f}")
table = pd.DataFrame({"coef": model.params, "p": model.pvalues})
print(table.round(4))
report(smf.ols("rides ~ temp_c", data=bikes).fit())
print()
report(smf.ols("rides ~ rain_mm", data=bikes).fit())rides ~ temp_c n=60 R2=0.726 adj R2=0.721
coef p
Intercept 135.8133 0.0
temp_c 12.5449 0.0
rides ~ rain_mm n=60 R2=0.168 adj R2=0.154
coef p
Intercept 380.1885 0.0000
rain_mm -11.2099 0.0011
Comparing the two reports: temperature explains much more of the variation (R² 0.726) than rain does on its own (R² 0.168).
Test yourself
Which part of the regression table contains the p-value of each coefficient?
- The top part
- The middle coefficient table
- The bottom diagnostics
- The title
Which attribute holds the estimated coefficients?
model.coefmodel.paramsmodel.summarymodel.values
Why do the lessons print summary2().tables[1] instead of the full summary()?
summary()is wrongsummary()includes the current date/time and is very widesummary2is faster to fitsummary()only works for one variable