DS Categorical Variables
Regression works with numbers, but many important variables are categories: weekday, station, weather type, membership plan. To use them in a model they must be encoded as numbers — and doing that the wrong way silently produces nonsense.
The wrong way: label codes
Numbering the weekdays 0–6 and using that number as a feature tells the model that Sunday (6) is "six times more Monday" than Tuesday (1), and that the effect grows by the same amount every day. Categories have no such order or spacing.
The right way: dummy (one-hot) variables
Give each category its own 0/1 column. pd.get_dummies does this:
import pandas as pd
trips = pd.DataFrame({
"station": ["Old Bridge", "Market Sq", "Riverside Park", "Old Bridge", "Market Sq"],
"minutes": [14, 32, 21, 9, 27],
})
print(pd.get_dummies(trips, columns=["station"], dtype=int))
print()
print(pd.get_dummies(trips, columns=["station"], drop_first=True, dtype=int)) minutes station_Market Sq station_Old Bridge station_Riverside Park
0 14 0 1 0
1 32 1 0 0
2 21 0 0 1
3 9 0 1 0
4 27 1 0 0
minutes station_Old Bridge station_Riverside Park
0 14 1 0
1 32 0 0
2 21 0 1
3 9 1 0
4 27 0 0
With drop_first=True, one category becomes the reference (here Market Sq, first alphabetically). It doesn't need a column: a row with zeros in all the others is the reference. Keeping all columns plus an intercept would make the columns perfectly redundant (the "dummy variable trap").
Our weekend column is already a dummy variable: 1 for weekend, 0 (the reference) for weekdays.
Categories in a statsmodels formula
The formula interface creates dummies automatically for text columns, or for any column wrapped in C(...):
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})
bikes["dow"] = bikes["date"].dt.day_name().str[:3]
m = smf.ols("rides ~ temp_c + rain_mm + C(dow, Treatment('Mon'))", data=bikes).fit()
coefs = m.params.rename(lambda name: name.replace("C(dow, Treatment('Mon'))", "dow"))
print(coefs.round(1))
print(f"\nadj R2 = {m.rsquared_adj:.3f}")Intercept 174.9
dow[T.Fri] -13.5
dow[T.Sat] 36.1
dow[T.Sun] 64.1
dow[T.Thu] -6.8
dow[T.Tue] -34.1
dow[T.Wed] -17.6
temp_c 11.3
rain_mm -9.3
dtype: float64
adj R2 = 0.917
Treatment('Mon') chooses Monday as the reference. Each weekday coefficient is the difference in rides compared with a Monday at the same temperature and rain. Sunday (+64) and Saturday (+36) stand out, while the other weekdays lie between −34 and −7 rides relative to Monday — differences of a size that day-to-day noise can easily produce with only 8–9 days per weekday.
Is a categorical variable useful overall?
A categorical variable with 7 levels adds 6 coefficients. Rather than judging each one separately, test them together with an F-test that compares the model with and without the variable:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from statsmodels.stats.anova import anova_lm
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})
bikes["dow"] = bikes["date"].dt.day_name()
base = smf.ols("rides ~ temp_c + rain_mm + weekend", data=bikes).fit()
full = smf.ols("rides ~ temp_c + rain_mm + C(dow)", data=bikes).fit()
print(anova_lm(base, full).round(4))
print()
print(f"AIC weekend-flag model: {base.aic:.1f}")
print(f"AIC 7-day model: {full.aic:.1f}") df_resid ssr df_diff ss_diff F Pr(>F)
0 56.0 58737.9207 0.0 NaN NaN NaN
1 51.0 49741.7966 5.0 8996.1242 1.8447 0.1207
AIC weekend-flag model: 591.5
AIC 7-day model: 591.5
The 7-day model spends 5 extra parameters but doesn't fit significantly better than the simple weekend flag (p ≈ 0.12), and its AIC is no lower (591.5 for both). The simple weekend/weekday split captures what matters — a good example of parsimony: prefer the simpler model when the data doesn't demand more.
High-cardinality categories
Categories with many levels (hundreds of stations, thousands of customers) create too many dummies. Common remedies:
- Group rare levels into "other":
s.where(s.map(s.value_counts()) >= 10, "other"). - Use a meaningful grouping instead: district instead of station.
- Target encoding (replace a level by the average target in that level) — powerful but leaks information unless computed on training data only.
import pandas as pd
stations = pd.Series(["Old Bridge"] * 6 + ["Market Sq"] * 5 + ["Mill Lane", "Harbour", "Old Bridge", "Zoo"])
counts = stations.value_counts()
grouped = stations.where(stations.map(counts) >= 3, "other")
print(grouped.value_counts())Old Bridge 7
Market Sq 5
other 3
Name: count, dtype: int64
Test yourself
Why shouldn't you code weekdays as 0–6 and use that number in a regression?
- Regression can't use integers
- It forces an order and equal spacing that categories don't have
- It creates too many columns
- It removes the intercept
With dummy coding and Monday as reference, the Saturday coefficient is +88. What does it mean?
- Saturdays have 88 rides
- Saturdays have about 88 more rides than Mondays with the same weather
- 88 % of rides are on Saturday
- Monday has 88 fewer rides than all other days
What is the "dummy variable trap"?
- Forgetting to encode categories
- Including a dummy for every category plus an intercept, making the columns perfectly redundant
- Using too few categories
- Using text columns in pandas