Patsy is a Python package for describing statistical models and for building design matrices, bringing R-style formulas to Python. The current version is 1.0.2. While no new feature development is planned, it maintains a maintenance cadence to ensure compatibility with current releases in the Python ecosystem.
pip install patsyVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `patsy.dmatrices` to generate design matrices from a formula string and a dictionary-like data source. It automatically handles categorical variables and adds an intercept term.
Upgrade to Python 3 or pin `patsy<1.0.0`.
Use `- 1` in the formula to remove the intercept, or `C(variable, contr.treatment)` for explicit coding options.
Explicitly set `NA_action='raise'` to catch missing values or implement custom handling before calling Patsy functions.
Wrap expressions meant for literal Python evaluation in `I()`, like `I(x**2)`.
Upgrade to `patsy>=1.0.0` if using `numpy>=2`.
Upgrade to `patsy>=1.0.2` if using `pandas>=3`.
Consider migrating to 'Formulaic' for new projects, while existing projects can continue to use Patsy for maintenance.
Install patsy using pip or conda: `pip install patsy` or `conda install patsy`.
Rename your conflicting variable (e.g., change `C = 1` to `my_C = 1`). Alternatively, for formula evaluation, you can explicitly pass `eval_env=0` (or a specific evaluation environment) to `patsy.dmatrix` or `statsmodels.formula.api.ols` to prevent local namespace lookups: `sm.ols('b ~ C(a)', data=df, eval_env=0).fit()`.Ensure that all variable names in your formula exactly match the column names in your DataFrame. If column names contain special characters (like '-', '+', ' '), rename them to be valid Python identifiers, or wrap them in `Q()` in the formula (e.g., `Q('CFC-11')`).Inspect your DataFrame for missing values (`df.isnull().sum()`) in the columns used in the formula. Patsy drops rows with NaNs by default. Ensure your data is clean and aligned before passing it to Patsy, or explicitly handle missing values (e.g., imputation or dropping them manually before calling Patsy).