How to Work with Categorical Variables in statsmodels

How to Work with Categorical Variables in statsmodels
Image by Editor | ChatGPT

Categorical variables are common in real-world data. They represent groups or labels, not numbers. Examples include gender, job type, or region. To use them in regression models, we must convert them into a numeric format, and understanding how this process works is crucial for obtaining reliable results.

In this article, we’ll explore how to handle categorical data in statsmodels.

What are Categorical Variables?

Categorical variables are variables that take on a limited number of distinct values. These values represent different categories or groups.

There are two main types of categorical variables:

  • Nominal: Categories with no inherent order (e.g. color, city, brand)
  • Ordinal: Categories with a logical order but unknown spacing (e.g. low, medium, high)

Since statistical models require numerical inputs, categorical variables must be encoded into numbers. This process needs to be done carefully to avoid introducing bias or incorrect relationships. The statsmodels library, along with patsy, provides built-in support for encoding categorical variables.

Example Dataset

Let’s take a look at a simple dataset to understand how categorical variables work in regression analysis.

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

# Example data
df = pd.DataFrame({
    'income': [50000, 60000, 55000, 52000, 58000, 62000],
    'education': ['HS', 'College', 'HS', 'Graduate', 'College', 'Graduate'],
    'age': [25, 30, 28, 40, 35, 45]
})

Using Patsy and Formulas with C()

The statsmodels library provides a convenient way to include categorical variables using the formula API. This approach leverages the patsy library to handle categorical encoding. The most common way to include categorical variables in a regression model is by using the C() wrapper in a formula. For example, C(education) tells patsy and statsmodels to treat education as a categorical variable.

model = smf.ols('income ~ C(education) + age', data=df).fit()
print(model.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                 income   R-squared:                       0.643
Model:                            OLS   Adj. R-squared:                  0.107
Method:                 Least Squares   F-statistic:                     1.200
Date:                Fri, 01 Aug 2025   Prob (F-statistic):              0.485
Time:                        07:39:46   Log-Likelihood:                -55.565
No. Observations:                   6   AIC:                             119.1
Df Residuals:                       2   BIC:                             118.3
Df Model:                           3                                         
Covariance Type:            nonrobust                                         
============================================================================================
                               coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------------
Intercept                  2.87e+04   2.66e+04      1.081      0.393   -8.56e+04    1.43e+05
C(education)[T.Graduate] -1.132e+04   9236.021     -1.226      0.345   -5.11e+04    2.84e+04
C(education)[T.HS]        -906.7797   6568.567     -0.138      0.903   -2.92e+04    2.74e+04
age                        932.2034    811.615      1.149      0.370   -2559.894    4424.300
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   1.937
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.646
Skew:                           0.000   Prob(JB):                        0.724
Kurtosis:                       1.393   Cond. No.                         541.
==============================================================================

Customizing Reference Categories

In statsmodels, the reference category for a categorical variable is the group against which all other categories are compared. By default, the first category in alphabetical order is used, but you can customize it using C(variable, Treatment(“desired_reference”)) in the model formula.

# Set 'HS' as the reference level
model = smf.ols("income ~ C(education, Treatment('HS')) + age", data=df).fit()

Using Interaction Terms

Interaction terms let you model how the effect of one variable depends on the level of another variable. In regression modeling with statsmodels, you can specify interactions using the : or * operators in the formula syntax:

  • : specifies an interaction only
  • * includes both the main effects and the interaction term
model = smf.ols('income ~ C(education) * age', data=df).fit()

Best Practices

Here are some best practices when handling categorical variables in statsmodels:

  • Always inspect your categories: Use df[‘column’].unique() or df[‘column’].cat.categories to verify what categories exist and ensure consistent formatting.
  • Set meaningful reference levels: Choose a reference category that makes interpretation easier, such as the most common or most neutral group.
  • Avoid multicollinearity: When encoding manually, always drop one dummy variable per categorical feature to avoid perfect multicollinearity.

Conclusion

Correctly handling categorical variables is essential for building reliable regression models in statsmodels. The C() function offers a straightforward way to include these variables, while tools like get_dummies() provide more manual control. By choosing meaningful reference categories, avoiding multicollinearity by dropping a dummy variable, and exploring interaction terms, you can build more accurate and interpretable models.

Leave a Reply

Your email address will not be published. Required fields are marked *