Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

This appendix collects, in one place, every piece of Python you need for MATH 4210. Use it to look up a function you saw in a chapter but forgot the syntax for, to set up Python on your own machine, or to review the whole toolkit before an exam. It is a reference, not a tutorial: for the reasoning behind any function, go back to the chapter where it first appears (each table entry below names that chapter).

D.1 Setting up Python

The book uses Python 3.12 or later, with three packages: pandas for data, statsmodels for model fitting, and matplotlib for plots. Install them once, in a terminal:

pip install pandas statsmodels matplotlib scipy

scipy comes along because statsmodels leans on it for distributions (t, F, chi-square) and because a few chapters call scipy.stats directly. Chapter 12 makes one brief appearance by sklearn for cross-validated shrinkage; install it only if you reach that chapter:

pip install scikit-learn

Every chapter’s Python code starts with the same three imports. Learn this block once and you will type it at the top of every script for the rest of the course:

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

pd reads and holds your data as a DataFrame (a table with named columns). np gives you array math: square roots, sums, matrix algebra. smf is the formula API, the part of statsmodels that lets you write a model the same way you say it out loud, sales ~ lotsize, rather than building matrices by hand. Chapters that plot also import matplotlib:

import matplotlib.pyplot as plt

All code in this book reads data with a relative path, data/toluca.csv, assuming you run Python from the book’s root folder. If you run a script from inside a chapter folder instead, adjust the path or set your working directory first.

D.2 The core workflow

Almost every example in this book follows the same four-step pattern. Learn this pattern and you can read (and write) any statsmodels analysis in the course.

df = pd.read_csv("data/toluca.csv")            # 1. load the data
fit = smf.ols("hours ~ lotsize", data=df).fit()  # 2. state the model, fit it
print(fit.summary())                             # 3. inspect the fit
pred = fit.predict(pd.DataFrame({"lotsize": [70]}))  # 4. use the fit

In words: you load a table, describe the model as a formula string (response on the left of ~, predictors on the right), call .fit() to estimate the coefficients, and then pull whatever you need off the fitted object, a summary table, individual numbers, residuals, or predictions at new x-values. Every table in Section D.4 is a variation on step 3 or step 4: some attribute or method you call on fit once you have it.

A fit object is not just numbers; it is a live Python object with named pieces. The two you will reach for constantly:

Formulas support the same shorthand throughout the book: y ~ x1 + x2 for multiple regression, y ~ x1 * x2 for two predictors plus their interaction, y ~ x1 + I(x1**2) for a squared term (the I() wrapper tells the formula parser “compute this, do not treat ** as formula syntax”), and y ~ C(group) to force a numeric-looking column to be treated as categorical.

D.3 Reading the tables below

Each chapter section lists the Python functions and methods that chapter uses, in the order they first appear, with a one-line description and a minimal runnable example. Examples use the book’s own datasets so you can paste them into a Python session and see real output. They are deliberately short: for the full worked analysis, see the chapter’s numbered examples and its code/chNN_examples.py file, which contains every code block from the chapter verbatim.

Some entries are pandas methods (Series.mean), some are numpy functions (numpy.sqrt), some are scipy distribution functions (scipy.stats.t.ppf), and some are methods on a fitted statsmodels object (fit.resid). The dotted path tells you where to find it: pandas.read_csv lives on the pd module, fit.resid lives on whatever object you got back from .fit().

D.4 Functions by chapter

Chapter 1: Regression as a way of thinking

Data: toluca.csv, salaries.csv, orings.csv, galton_heights.csv, anscombe.csv

FunctionWhat it doesExample
pandas.read_csvLoads a CSV file into a DataFramedf = pd.read_csv("data/toluca.csv")
statsmodels.formula.api.olsStates a linear model from a formulafit = smf.ols("hours ~ lotsize", data=df).fit()
fit.paramsCoefficient estimates, by namefit.params["lotsize"]
fit.predictPredicted values at new xfit.predict(pd.DataFrame({"lotsize": [70]}))
Series.meanColumn meandf["hours"].mean()
Series.minColumn minimumdf["hours"].min()
Series.corrCorrelation between two columnsdf["lotsize"].corr(df["hours"])
Series.varColumn variancedf["hours"].var()
lenNumber of rows (built-in Python)len(df)
pandas.DataFrameBuilds a small table by handpd.DataFrame({"lotsize": [70]})
DataFrame.roundRounds every numeric columndf.round(2)
numpyThe numeric-array moduleimport numpy as np

Chapter 2: Simple linear regression

Data: toluca.csv, toluca_mini.csv (see 2.1 The simple linear regression model, 2.2 Least squares from first principles)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/toluca.csv")
statsmodels.formula.api.olsFits the simple linear regression modelfit = smf.ols("hours ~ lotsize", data=df).fit()
fit.paramsThe estimates b0, b1fit.params["Intercept"]
fit.predictFitted value or prediction at new xfit.predict(df)
fit.residResiduals e_i = y_i - yhat_ifit.resid
fit.fittedvaluesFitted values yhat_ifit.fittedvalues
fit.summaryFull regression reportprint(fit.summary())
numpy.sumSum of an arraynp.sum(fit.resid ** 2)
numpy.sqrtSquare rootnp.sqrt(mse)
numpy.polyfitLeast-squares polynomial fit by hand (bypasses statsmodels)np.polyfit(df["lotsize"], df["hours"], 1)
numpy.random.default_rngSeeded random number generatorrng = np.random.default_rng(4210)
rng.normalDraws normal random valuesrng.normal(0, 1, size=10)

Chapter 3: Inference for simple linear regression

Data: toluca.csv, advertising.csv (see 3.6 The analysis of variance approach, 3.7 The F test and its equivalence to the t test, 3.5 Prediction interval for a new observation)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/toluca.csv")
statsmodels.formula.api.olsFits the modelfit = smf.ols("hours ~ lotsize", data=df).fit()
fit.summaryCoefficients, SEs, t, p, R-squared, Fprint(fit.summary())
fit.conf_intConfidence intervals for coefficientsfit.conf_int(alpha=0.05)
fit.paramsCoefficient estimatesfit.params
fit.residResidualsfit.resid
fit.fittedvaluesFitted valuesfit.fittedvalues
fit.get_predictionPrediction object for CI or PI at new xpr = fit.get_prediction(pd.DataFrame({"lotsize": [70]}))
get_prediction.conf_intCI (or PI with obs=True) from a prediction objectpr.conf_int(obs=True, alpha=0.05)
statsmodels.api.stats.anova_lmANOVA table for a fitted modelsm.stats.anova_lm(fit)
scipy.stats.t.ppft distribution quantile (critical value)stats.t.ppf(0.975, df=23)
scipy.stats.f.ppfF distribution quantilestats.f.ppf(0.95, 1, 23)
numpy.random.default_rngSeeded RNGrng = np.random.default_rng(4210)
numpy.sumSum of an arraynp.sum(fit.resid ** 2)
numpy.sqrtSquare rootnp.sqrt(mse)

Chapter 4: Correlation

Data: savings.csv, anscombe.csv, galton_heights.csv (see 4.2 Correlation and the regression slope)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/savings.csv")
DataFrame.corrCorrelation matrix of all numeric columnsdf.corr(numeric_only=True)
Series.corrCorrelation between two columnsdf["sr"].corr(df["ddpi"])
statsmodels.formula.api.olsFits the regression to compare against rfit = smf.ols("sr ~ ddpi", data=df).fit()
fit.paramsCoefficient estimatesfit.params
fit.rsquaredR-squared (equals r^2 in simple regression)fit.rsquared
fit.tvaluest statistics for each coefficientfit.tvalues
fit.pvaluesp-values for each coefficientfit.pvalues
scipy.stats.pearsonrPearson r with its p-valuestats.pearsonr(df["sr"], df["ddpi"])
scipy.stats.spearmanrSpearman rank correlationstats.spearmanr(df["sr"], df["ddpi"])
scipy.stats.norm.ppfNormal quantile (for the Fisher z interval)stats.norm.ppf(0.975)
numpy.arctanhFisher z transform of rnp.arctanh(r)
numpy.tanhInverse Fisher z transformnp.tanh(z)
numpy.corrcoefCorrelation matrix from arraysnp.corrcoef(df["sr"], df["ddpi"])
numpy.random.default_rngSeeded RNGrng = np.random.default_rng(4210)
DataFrame.groupbySplits a table by a grouping columndf.groupby("country").mean(numeric_only=True)

Chapter 5: Randomization and bootstrap inference for regression

Data: punting.csv, toluca.csv (see 5.2 The permutation test for the slope, 5.4 The bootstrap for regression)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/punting.csv")
statsmodels.formula.api.olsFits the observed modelfit = smf.ols("Distance ~ RStr", data=df).fit()
fit.summaryFull reportprint(fit.summary())
fit.pvaluesp-values for each coefficientfit.pvalues
fit.bseStandard errors of the coefficientsfit.bse
fit.conf_intConfidence intervalsfit.conf_int()
numpy.random.default_rngSeeded RNG that drives every resamplerng = np.random.default_rng(4210)
rng.permutationShuffles an array (for a permutation test)rng.permutation(df["Distance"].to_numpy())
rng.integersRandom integer indices (for bootstrap resampling)rng.integers(0, len(df), size=len(df))
rng.choiceRandom sample with replacementrng.choice(df.index, size=len(df), replace=True)
numpy.sum, numpy.mean, numpy.stdBasic array summariesnp.mean(boot_slopes)
numpy.quantilePercentile of an array (bootstrap CI endpoints)np.quantile(boot_slopes, [0.025, 0.975])
numpy.absAbsolute valuenp.abs(t_stat)
numpy.maxMaximum of an arraynp.max(perm_slopes)
numpy.empty, numpy.array, numpy.asarrayPreallocate or build arrays for a resampling loopboot_slopes = np.empty(2000)

Chapter 6: Matrix algebra for regression

Data: dwaine.csv (see 6.2 Transpose and matrix multiplication, 6.4 The inverse and the normal equations, 6.5 Idempotent and projection matrices, 6.7 Random vectors, expectation, and covariance matrices, 6.8 The multivariate normal, in brief)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/dwaine.csv")
numpy.column_stackBuilds the design matrix X from columnsX = np.column_stack([np.ones(len(df)), df["targtpop"], df["dispoinc"]])
numpy.onesA column of 1s, for the interceptnp.ones(len(df))
numpy.arrayBuilds an array or vector by handy = np.array(df["sales"])
numpy.allcloseChecks two arrays are equal within rounding errornp.allclose(X @ b, fit.fittedvalues)
numpy.linalg.matrix_rankRank of a matrixnp.linalg.matrix_rank(X)
numpy.linalg.detDeterminant of a square matrixnp.linalg.det(X.T @ X)
numpy.linalg.invMatrix inversenp.linalg.inv(X.T @ X)
numpy.roundRounds every entry of an arraynp.round(X.T @ X, 2)
numpy.traceSum of the diagonal (trace)np.trace(H)
numpy.eyeIdentity matrixnp.eye(3)
numpy.sqrtSquare rootnp.sqrt(np.diag(cov))
numpy.diagExtracts or builds a diagonalnp.diag(H)
numpy.linalg.choleskyCholesky factor of a covariance matrixnp.linalg.cholesky(sigma)
numpy.covSample covariance matrixnp.cov(X, rowvar=False)
numpy.random.default_rngSeeded RNGrng = np.random.default_rng(4210)
rng.standard_normalDraws standard normal valuesrng.standard_normal((100, 3))
statsmodels.formula.api.olsFits the model to check the matrix formulasfit = smf.ols("sales ~ targtpop + dispoinc", data=df).fit()
fit.paramsCoefficient estimates, to compare against b = (X’X)^-1 X’yfit.params
fit.summary2Alternate summary report, easier to read programmaticallyfit.summary2()

Chapter 7: The general linear model

Data: dwaine.csv, toluca.csv (see 7.1 The model and least squares in matrix form, 7.3 The hat matrix, 7.6 The Gauss-Markov theorem, 7.2 The geometry of least squares)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/dwaine.csv")
numpy.column_stackBuilds the design matrixX = np.column_stack([np.ones(len(df)), df["targtpop"], df["dispoinc"]])
numpy.onesIntercept columnnp.ones(len(df))
numpy.linalg.invMatrix inverse, for (X’X)^-1np.linalg.inv(X.T @ X)
numpy.traceTrace of the hat matrix (equals p)np.trace(H)
numpy.diagDiagonal entries (leverages h_ii)np.diag(H)
numpy.sqrtSquare rootnp.sqrt(mse)
numpy.allcloseChecks agreement between hand and statsmodels fitsnp.allclose(b, fit.params)
numpy.roundRounds for displaynp.round(H, 3)
statsmodels.formula.api.olsFits the model directlyfit = smf.ols("sales ~ targtpop + dispoinc", data=df).fit()
numpy.random.default_rngSeeded RNGrng = np.random.default_rng(4210)

Chapter 8: Multiple regression in practice

Data: dwaine.csv, bodyfat3.csv, savings.csv (see 8.3 Extra sums of squares, 8.4 The general linear test, 8.5 Added-variable plots)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/bodyfat3.csv")
statsmodels.formula.api.olsFits the full or reduced modelfit = smf.ols("bodyfat ~ triceps + thigh + midarm", data=df).fit()
fitThe fitted-model object itself, reused across a general linear testfull = smf.ols("bodyfat ~ triceps + thigh + midarm", data=df).fit()
fit.paramsCoefficient estimatesfit.params
fit.ssrError sum of squares, SSEfit.ssr
fit.residResidualsfit.resid
fit.tvaluest statisticsfit.tvalues
fit.df_residResidual degrees of freedomfit.df_resid
fit.rsquaredR-squaredfit.rsquared
fit.rsquared_adjAdjusted R-squaredfit.rsquared_adj
statsmodels.api.OLSLower-level OLS constructor (matrix input, not a formula)sm.OLS(y, X).fit()
numpy.polyfitQuick polynomial fit outside statsmodelsnp.polyfit(df["thigh"], df["bodyfat"], 1)

Chapter 9: Model diagnostics

Data: gala.csv, savings.csv, toluca.csv (see 9.1 Leverage values and the hat matrix points, 9.2 Four flavors of residual, 9.3 Influence: which points actually change the fit)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/gala.csv")
statsmodels.formula.api.olsFits the modelfit = smf.ols("Species ~ Area + Elevation", data=df).fit()
fit.get_influenceBuilds the influence-diagnostics objectinfl = fit.get_influence()
influence.hat_matrix_diagLeverages h_iiinfl.hat_matrix_diag
influence.resid_studentized_internalInternally studentized residualsinfl.resid_studentized_internal
influence.resid_studentized_externalExternally studentized (deleted) residualsinfl.resid_studentized_external
influence.cooks_distanceCook’s distance for each observationinfl.cooks_distance[0]
influence.dffitsDFFITS for each observationinfl.dffits[0]
influence.dfbetasDFBETAS for each coefficient and observationinfl.dfbetas
fit.residRaw residualsfit.resid
fit.fittedvaluesFitted valuesfit.fittedvalues
fit.rsquaredR-squaredfit.rsquared
fit.scaleMSE (estimated error variance)fit.scale
fit.ssrSSEfit.ssr
statsmodels.stats.api.het_breuschpaganBreusch-Pagan test for non-constant variancesm.stats.het_breuschpagan(fit.resid, fit.model.exog)
scipy.stats.shapiroShapiro-Wilk test for normality of residualsstats.shapiro(fit.resid)
scipy.stats.t.ppft quantile for a cutoff linestats.t.ppf(0.975, df=fit.df_resid)
scipy.stats.f.sfUpper-tail F probability (Cook’s distance benchmark)stats.f.sf(d, 3, fit.df_resid)
statsmodels.stats.stattools.durbin_watsonDurbin-Watson statisticdurbin_watson(fit.resid)
numpy.random.default_rngSeeded RNGrng = np.random.default_rng(4210)
numpy.argsortIndices that would sort an arraynp.argsort(infl.cooks_distance[0])
numpy.argmaxIndex of the largest valuenp.argmax(infl.cooks_distance[0])

Chapter 10: Remedial measures and transformations

Data: mammals.csv, cars.csv, strongx.csv, gala.csv, savings.csv

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/mammals.csv")
numpy.logNatural log, for a log-log modelnp.log(df["body"])
numpy.sqrtSquare root, a milder variance-stabilizing transformnp.sqrt(df["body"])
statsmodels.formula.api.olsFits an ordinary least-squares modelfit = smf.ols("np.log(brain) ~ np.log(body)", data=df).fit()
statsmodels.formula.api.wlsFits a weighted least-squares modelfit = smf.wls("dist ~ speed", data=df, weights=w).fit()
statsmodels.formula.api.rlmFits a robust regression, resistant to outliersfit = smf.rlm("dist ~ speed", data=df).fit()
numpy.linalg.lstsqDirect least-squares solve, outside the formula APIb, *_ = np.linalg.lstsq(X, y, rcond=None)
numpy.column_stackBuilds a design matrixX = np.column_stack([np.ones(len(df)), df["speed"]])
fit.paramsCoefficient estimatesfit.params
fit.rsquaredR-squaredfit.rsquared
fit.bseStandard errorsfit.bse
fit.predictPredicted valuesfit.predict(df)
fit.weightsThe weights used in a WLS fitfit.weights
fit.get_influenceInfluence diagnostics on the fitfit.get_influence()
numpy.arangeEvenly spaced values, for a grid to plot overnp.arange(0, 25, 0.5)
numpy.argmaxIndex of the largest valuenp.argmax(resid ** 2)
pandas.SeriesBuilds a labeled 1-D arraypd.Series(weights)
pandas.DataFrameBuilds a small table by handpd.DataFrame({"speed": grid})

Chapter 11: Categorical predictors and interactions

Data: salaries.csv, cars.csv (see 11.1 From categories to numbers: indicator coding, 11.2 One categorical and one continuous predictor, 11.4 Polynomial regression and centering)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/salaries.csv")
pandas.CategoricalMarks a column as categorical, with a chosen level orderdf["rank"] = pd.Categorical(df["rank"], categories=["AsstProf", "AssocProf", "Prof"])
pandas.DataFrame.renameRenames columnsdf.rename(columns={"yrs.since.phd": "yrs_phd"})
pandas.DataFrame.groupbySplits by group, for group meansdf.groupby("rank")["salary"].mean()
pandas.DataFrame.value_countsCounts of each categorydf["rank"].value_counts()
statsmodels.formula.api.olsFits a model with dummy coding or interactionsfit = smf.ols("salary ~ C(rank) * sex", data=df).fit()
fit.paramsCoefficient estimates, including dummy contrastsfit.params
fit.summary2Alternate summary reportfit.summary2()
fit.predictPredicted values at new rowsfit.predict(newdata)
fit.model.exogThe numeric design matrix statsmodels built from the formulafit.model.exog
fit.fvalueOverall F statisticfit.fvalue
statsmodels.stats.anova.anova_lmANOVA table, e.g. to test an interaction termanova_lm(reduced, full)
numpy.corrcoefCorrelation matrix from arraysnp.corrcoef(df["speed"], df["dist"])
CFormula wrapper that forces categorical treatmentsmf.ols("salary ~ C(discipline)", data=df)
TreatmentChooses the reference level inside C()C(rank, Treatment(reference="AsstProf"))

Chapter 12: Multicollinearity, variable selection, and validation

Data: fat.csv (see 12.1 Multicollinearity and the variance inflation factor, 12.2 Choosing among models: selection criteria, 12.4 Validation: train, test, and cross-validate, 12.5 A look at shrinkage: ridge and lasso)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/fat.csv")
smf.olsFits a candidate modelfit = smf.ols("brozek ~ age + weight + height", data=df).fit()
numpy.linalg.lstsqDirect least-squares solvenp.linalg.lstsq(X, y, rcond=None)
itertools.combinationsGenerates predictor subsets for best-subsets searchlist(combinations(predictors, 3))
get_influence().hat_matrix_diagLeverages, used inside a validation loopfit.get_influence().hat_matrix_diag
numpy.random.default_rngSeeded RNG for the train/test splitrng = np.random.default_rng(4210)
sklearn.linear_model.LassoCVLasso regression with built-in cross-validationLassoCV(cv=10).fit(X, y)
sklearn.linear_model.RidgeCVRidge regression with built-in cross-validationRidgeCV(cv=10).fit(X, y)
sklearn.linear_model.LassoLasso at a fixed penaltyLasso(alpha=0.5).fit(X, y)
sklearn.preprocessing.StandardScalerStandardizes predictors before shrinkageStandardScaler().fit_transform(X)

Chapter 13: Logistic regression

Data: orings.csv, pima.csv (see 13.1 Why a straight line fails, and what to use instead, 13.3 Reading coefficients as odds ratios, 13.2 Fitting by maximum likelihood)

FunctionWhat it doesExample
statsmodels.formula.api.glmFits a generalized linear modelfit = smf.glm("damage ~ temp", data=df, family=sm.families.Binomial()).fit()
statsmodels.api.families.BinomialThe binomial family, for logistic regressionsm.families.Binomial()
fit.summaryFull GLM reportprint(fit.summary())
fit.predictPredicted probabilitiesfit.predict(pd.DataFrame({"temp": [31]}))
fit.paramsCoefficient estimates, on the log-odds scalefit.params
fit.conf_intConfidence intervals for the coefficientsfit.conf_int()
scipy.stats.chi2.sfUpper-tail chi-square probability, for a deviance teststats.chi2.sf(dev_diff, df=1)
pandas.crosstabTwo-way count tablepd.crosstab(df["test"], df["glucose"] > 140)
numpy.expExponentiates log-odds to get oddsnp.exp(fit.params)
numpy.linalg.solveSolves a linear system (used inside Newton-Raphson by hand)np.linalg.solve(info, score)

Chapter 14: Poisson regression and the GLM idea

Data: gala.csv, ships.csv, toluca.csv (see 14.1 Why counts break the linear model, 14.6 One family: the generalized linear model)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/ships.csv")
statsmodels.formula.api.glmFits a GLMfit = smf.glm("incidents ~ type + year", data=df, family=sm.families.Poisson()).fit()
statsmodels.api.families.PoissonThe Poisson family, for count datasm.families.Poisson()
statsmodels.api.families.GaussianThe Gaussian family (ordinary regression as a GLM)sm.families.Gaussian()
statsmodels.formula.api.olsFits ordinary least squares, for comparisonsmf.ols("Species ~ Area", data=df).fit()
numpy.expExponentiates the linear predictor to get a ratenp.exp(fit.params)
numpy.logNatural log, the Poisson link functionnp.log(df["incidents"] + 1)
fit.paramsCoefficient estimatesfit.params
fit.bseStandard errorsfit.bse
fit.fittedvaluesFitted mean countsfit.fittedvalues
fit.resid_pearsonPearson residualsfit.resid_pearson
fit.df_residResidual degrees of freedomfit.df_resid

Chapter 15: Regression with time: autocorrelation and forecasting

Data: airpassengers.csv (see 15.2 Why time breaks ordinary least squares, 15.5 Forecasting honestly: test on the future)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/airpassengers.csv")
numpy.arangeBuilds a time indexnp.arange(len(df))
numpy.logLog transform to stabilize a multiplicative trendnp.log(df["passengers"])
numpy.expUndoes a log transform to return to the original scalenp.exp(pred_log)
statsmodels.formula.api.olsFits the trend modelfit = smf.ols("np.log(passengers) ~ t", data=df).fit()
fit.paramsCoefficient estimatesfit.params
fit.rsquaredR-squaredfit.rsquared
fit.scaleMSEfit.scale
fit.residResiduals, inspected for leftover autocorrelationfit.resid
fit.fittedvaluesFitted valuesfit.fittedvalues
fit.model.exogDesign matrix, used to build a forecast rowfit.model.exog
fit.get_predictionPrediction object, for a prediction intervalfit.get_prediction(newdata)
statsmodels.stats.stattools.durbin_watsonDurbin-Watson statistic for autocorrelated residualsdurbin_watson(fit.resid)
numpy.diffDifferences consecutive values (a simple detrending step)np.diff(df["passengers"])
numpy.linalg.lstsqDirect least-squares solve for a Cochrane-Orcutt style fitnp.linalg.lstsq(X, y, rcond=None)
numpy.random.default_rngSeeded RNGrng = np.random.default_rng(4210)
rng.standard_normalSimulated normal errors, for a forecast demonstrationrng.standard_normal(12)
numpy.sqrtSquare rootnp.sqrt(mse)
numpy.meanMean of an arraynp.mean(errors)

Chapter 16: Path analysis and a look ahead

Data: duncan.csv (see 16.1 Drawing a causal story: path diagrams)

FunctionWhat it doesExample
pandas.read_csvLoads a CSV filedf = pd.read_csv("data/duncan.csv")
statsmodels.formula.api.olsFits each structural equation in the path modelfit = smf.ols("prestige ~ income + education", data=df).fit()
fit.paramsPath-coefficient estimatesfit.params
DataFrame.corrCorrelation matrix among all variables in the path diagramdf.corr(numeric_only=True)
DataFrame.meanColumn meansdf.mean(numeric_only=True)
DataFrame.stdColumn standard deviationsdf.std(numeric_only=True)
Series.corrCorrelation between two variablesdf["income"].corr(df["prestige"])
numpyThe numeric-array moduleimport numpy as np

D.5 Common errors and fixes