Panel regression in Python: fixed and random effects, step by step
TL;DR
Difficulty: Advanced
- Data with a who (shops) and a when (quarters) is a panel. Pooled OLS on all rows finds 698 transactions per thousand newsletters where the truth built into the data is 380, and gets the sign of price backwards.
- Two way fixed effects (PanelOLS with shop and quarter effects, or dummies in statsmodels) recover 379, 200 and minus 493 against a true 380, 210 and minus 440.
- Measure the within share first: price moves only 6.2% within shops, so its estimate is the shakiest.
- With five shops, linearmodels' random effects silently collapses to pooled OLS and the classic Hausman statistic comes out negative. Use statsmodels mixedlm and the Mundlak test instead.
- With five clusters no wild bootstrap p value can fall below 0.0625. Judge a broken shop by a holdout: Bishopstown's 2025 gap is 4,900 transactions, about €71,000.
The Marketing Analytics chapter on panel regression explained why five shops added together lie about marketing. This chapter builds the whole analysis in Python on data you generate yourself, with pandas, statsmodels and linearmodels, and shows the three traps that run without an error message. Same invented chain, Heron Pantry, and the same question: is Bishopstown a bad shop, or did it have a bad year?
The question, and where the concepts already live
"How do I run panel regressions with fixed and random effects in Python, as in the same store sales chapter?" That is the question this chapter answers, line by line.
The concepts are explained in the Marketing Analytics chapter Panel regression and same store sales: why pooling five shops lets shop size leak into every marketing number, what fixed and random effects are, what the Hausman test asks, why errors should be clustered, and how like for like sales are the simple cousin of the whole idea. This chapter builds it. Same invented chain, Heron Pantry, five delicatessens in Cork and Galway, twelve quarters from 2023 to 2025, and the same owner, Niamh, asking the same question: "Is Bishopstown a bad shop, or did Bishopstown have a bad year?"
The data are generated in code to resemble the example in that chapter, so every block below runs as it stands. Because the data are generated here, the true answer is known: in the code, every thousand newsletter sends adds 380 transactions, every €1,000 of paid social adds 210, and every 25 cent on the average item price costs 440. That makes this chapter a fair test of the estimators. The ones that find 380, 210 and minus 440 are telling the truth. The ones that do not are telling you something about the shops instead.
If you are new to the building blocks, the chapter on joining and reshaping data with merge, concat, pivot and melt covers the long tables and the MultiIndex this chapter leans on, and statistical models in Python with statsmodels and scikit learn covers the formula interface.
For the person who commissions this
If you only read one section, read this one.
Whenever your data have a "who" (shops, markets, client accounts) and a "when" (weeks, months, quarters), adding everything up or throwing every row into one regression mixes two questions: which units are bigger, and what happens when a unit does more. Marketing coefficients from such a regression mostly measure size. In this chapter's example the pooled regression says a thousand newsletters are worth 698 transactions. The truth in the data is 380. It also says higher prices go with more sales, when in truth they cost sales.
Fixed effects fix that by comparing each shop only with itself. They recover 379, 200 and minus 493 against the true 380, 210 and minus 440. That is the number to plan with.
Four things to ask whoever runs the analysis:
- Did you compare each unit with its own history (fixed effects), and did the marketing numbers shrink when you did? If they shrank a lot, the old numbers were measuring size.
- Did you remove what hit every unit at once, such as the season or a national campaign (time effects)? Forgetting this in the example triples the paid social effect.
- How many units are there? With five, no p value deserves a star. In the example even an effect that is twelve standard errors from zero cannot get below a p value of 0.0625 by the method built for few groups.
- Which unit is drifting away from its own history, and how much is that worth? For Bishopstown the answer is roughly 4,900 transactions in 2025, about €71,000 of sales.
The check before any model: how much moves within a shop?
Here is the idea I would put first, because no tutorial I know of does. Fixed effects throw away every difference between shops and keep only the movement within each shop over time. So before you fit anything, measure how much of each variable is left once you do that. I call it the within share:
where is the variable (say newsletter sends) at shop in quarter , is shop 's own average over the twelve quarters, is the average over all 60 rows, and is the share of the total variation that is movement within shops. A share near 1 means the shops look alike and move a lot. A share near 0 means the variable mostly tells you which shop you are in, and fixed effects will have very little to learn from. The averages are in Foundations: the mean, and the sum of squared deviations is the variance in Foundations: spread.
My rule of thumb: below about 10%, expect wide error margins from fixed effects and say so before anyone sees a coefficient. Below about 3%, do not fit the model at all. Draw each shop's line and talk about it. This is not a statistical law, it is a planning rule. It tells you in one minute whether a panel model can answer the question at all, and it warns you which coefficient will be the shaky one.
Example: the within share at Heron Pantry
First the data. The code below builds the panel: one row per shop and quarter. The shop table holds what makes each shop different (floor space, a base level of trade, typical marketing and prices). The loop adds the season, a slow growth in marketing, noise that carries over from one quarter to the next, and, hidden from the analyst, the Sunday hours cut at Bishopstown in 2025 that the Marketing Analytics chapter uncovers.
python -m pip install "pandas==3.0.2" "numpy==2.4.4" "statsmodels==0.14.6" "linearmodels==7.0" "scipy==1.17.1"
These are the versions current in April 2026: Python 3.14, pandas 3.0, NumPy 2.4, statsmodels 0.14 and linearmodels 7.0, released in October 2025.1 The first chapter of the foundations series shows how to set up the environment.
import itertools
import warnings
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from linearmodels.panel import PanelOLS, RandomEffects
from scipy import stats
rng = np.random.default_rng(3521)
# Five invented shops: what makes each one different
shops = pd.DataFrame({
"shop": ["Douglas", "Knocknacarra", "Bishopstown", "Renmore", "Blackrock"],
"floor_m2": [360, 240, 225, 190, 170],
"base": [21200, 13400, 14500, 11900, 10900], # trade not explained by marketing
"email_k": [28.0, 18.5, 15.0, 13.0, 9.5], # newsletter sends, thousands per quarter
"social_k": [8.0, 6.8, 5.4, 4.1, 3.1], # paid social, € thousands per quarter
"price": [4.95, 4.15, 3.85, 3.70, 3.15], # average item price, €
})
quarters = pd.period_range("2023Q1", "2025Q4", freq="Q")
season = {1: 0, 2: 2400, 3: 6200, 4: 1800} # extra transactions against Q1
sunday_cut = {1: 900, 2: 1300, 3: 2000, 4: 1800} # Bishopstown 2025, unknown to the analyst
rows = []
for s in shops.itertuples():
carry = 0.0 # what the model misses, partly carried over
for t, q in enumerate(quarters):
email = s.email_k * (1 + 0.03 * t) * rng.normal(1, 0.08)
social = s.social_k * (1 + 0.06 * t) * rng.normal(1, 0.15)
price = s.price + rng.normal(0, 0.15)
carry = 0.5 * carry + rng.normal(0, 400)
y = (s.base + season[q.quarter]
+ 380 * email + 210 * social - 440 * price / 0.25 # the true effects
+ carry)
if s.shop == "Bishopstown" and q.year == 2025:
y -= sunday_cut[q.quarter]
rows.append({"shop": s.shop, "quarter": str(q), "qdate": q.start_time,
"transactions": round(y), "email_k": round(email, 1),
"social_k": round(social, 2), "price": round(price, 2)})
df = pd.DataFrame(rows)
df["price25"] = df["price"] / 0.25 # price in steps of 25 cent
print(df.shape) # (60, 8)
Two columns describe time on purpose. quarter is text such as "2025Q3", which the statsmodels formulas need. qdate is a real date, which linearmodels needs. Why not one Period column for both? Inside C(...) in a statsmodels 0.14 formula, a pandas Period column stops with the error Cannot interpret 'period[Q-DEC]' as a data type. Text sidesteps it. In pandas 3.0 that text column is stored with the new default string type, which the formulas read without trouble. McKinney's book was written for older pandas versions; nothing in this chapter depends on the 3.0 changes beyond that.
A few rows, so you can see the shape. Note the flagship's numbers against Blackrock's:
| shop | quarter | transactions | email_k | social_k | price |
|---|---|---|---|---|---|
| Douglas | 2025Q3 | 35,432 | 34.6 | 16.59 | 5.14 |
| Bishopstown | 2025Q3 | 20,892 | 20.0 | 10.81 | 4.18 |
| Blackrock | 2025Q3 | 16,007 | 12.2 | 3.91 | 3.18 |
| Bishopstown | 2025Q1 | 14,085 | 17.2 | 7.09 | 3.69 |
Now the within share, one small function using groupby and transform from the chapter on group by and pivot tables:
def within_share(data, col, unit="shop"):
"""Share of a column's variance left after removing each unit's own mean."""
within = data[col] - data.groupby(unit)[col].transform("mean")
return within.var() / data[col].var()
for col in ["transactions", "email_k", "social_k", "price25"]:
print(f"{col:13} {within_share(df, col):.1%}")
# transactions 15.4%
# email_k 11.1%
# social_k 29.0%
# price25 6.2%
Read it like this. Only 15.4% of the variation in transactions happens within shops. The rest is "which shop is it". Newsletter sends are 11.1% within, just above my 10% line. Paid social moves the most within shops, at 29.0%. Price moves least, 6.2%: the shops keep their price levels, and that is where the widest error margin will be. So before any model runs, you already know that the price coefficient will be the least precise of the three, and that the pooled regression will be dominated by the differences between shops.
Long data with a MultiIndex: shop first, then quarter
Panel data in Python are a long table, one row per unit per period, with a two level index. In pandas that is a MultiIndex (an index with several levels, explained in McKinney's chapter on data wrangling).2 linearmodels reads it in a fixed order: the outer level is the entity, the inner level is time, and the time level must be numeric or a date.3
That order is not a style choice. It decides what the software thinks a unit is.
Example: setting and checking the panel index
panel = df.set_index(["shop", "qdate"]).sort_index()
# Three checks before any model
print(panel.index.is_unique) # True: one row per shop and quarter
print(panel.groupby(level="shop").size().unique()) # [12]: every shop has 12 quarters
print(panel.index.get_level_values("shop").nunique()) # 5 shops
If the first check says False, you have duplicate rows, often a refund booked as a second row for the same shop and quarter. If the second shows several numbers, the panel is unbalanced (a shop opened or closed), which the models handle, but which changes like for like sales, as you will see further down. If the third says 6 when you have five shops, a shop name is spelled two ways, usually a trailing space or "Douglas (Cork)" in one export. df["shop"].str.strip() and a small mapping table, as in the chapter on cleaning data in pandas, fix it before it splits one shop into two.
Example: the swapped index that runs without complaint
Here is the trap. Many till exports use numeric shop codes, and many analysts number the quarters 1 to 12. Then both levels are numbers, and nothing stops you from putting them in the wrong order:
df["shop_id"] = pd.factorize(df["shop"])[0] + 101 # shop codes 101 to 105
df["period"] = df.groupby("shop").cumcount() + 1 # quarters 1 to 12
X = ["email_k", "social_k", "price25"]
right = df.set_index(["shop_id", "period"])
wrong = df.set_index(["period", "shop_id"]) # quarter first: wrong
for name, p in [("right", right), ("wrong", wrong)]:
one_way = PanelOLS(p["transactions"], p[X], entity_effects=True).fit()
print(name, one_way.entity_info["total"], one_way.params.round(0).to_dict())
# right 5.0 {'email_k': 111.0, 'social_k': 776.0, 'price25': 228.0}
# wrong 12.0 {'email_k': 698.0, 'social_k': 81.0, 'price25': 182.0}
The wrong version runs, prints a tidy table and reports 12 entities. It has compared each quarter with itself, which is the pooled regression in disguise. Neither line is right, by the way: the "right" one shows a different mistake, which the section on time effects explains. The habit that saves you is to print entity_info["total"] every time. It should be the number of shops.
Pooled OLS: one regression on all 60 rows
Pooled ordinary least squares (OLS) is what the marketing team did in a spreadsheet: one line through every row, with quarter dummies so the season does not pollute the result. In the notation of the Marketing Analytics chapter:
where is till transactions at shop in quarter , is one intercept for every shop, is the effect of quarter , is newsletter sends in thousands, is paid social in thousands of euro, is the average item price in steps of 25 cent, to are the effects you are after, and is everything else. The problem is that contains "this is the flagship", and the flagship also sends more newsletters and charges more. The regression itself is explained in Foundations: regression.
Example: the pooled regression flatters the newsletter
pooled = smf.ols(
"transactions ~ email_k + social_k + price25 + C(quarter)", data=df
).fit()
print(pooled.params[X].round(0))
# email_k 698.0
# social_k 81.0
# price25 182.0
print(round(pooled.rsquared, 3)) # 0.971
An R squared of 0.971 looks excellent, and every number is wrong. The newsletter effect of 698 is almost twice the true 380. Paid social at 81 looks nearly useless, against a true 210. And price comes out positive: 182 more transactions for every 25 cent. That is the flagship talking. It is the biggest shop, it sends the most newsletters and it charges the most, so in the pooled data all three travel together. The high R squared is the giveaway, not the comfort: it is mostly explaining which shop is which.
Fixed effects: compare each shop with itself
The two way fixed effects model gives every shop its own intercept and every quarter its own effect :
where absorbs everything about shop that does not change over the three years (size, location, the café) and the other symbols are as before. Subtracting each shop's own average from every column, the within transformation, removes exactly, because a constant minus its own average is zero. The Marketing Analytics chapter writes it out in full. What matters for the code is that there are three ways to compute it, and they must agree to the last decimal.4 The averages being subtracted are in Foundations: the mean.
Example: three routes to the same fixed effects
formula = "transactions ~ email_k + social_k + price25 + C(shop) + C(quarter)"
# 1) Dummy variables: one column per shop and per quarter
fe_dummies = smf.ols(formula, data=df).fit()
# 2) The within transformation by hand: subtract each shop's own mean
cols = ["transactions"] + X
demeaned = df[cols] - df.groupby("shop")[cols].transform("mean")
demeaned["quarter"] = df["quarter"]
fe_within = smf.ols(
"transactions ~ email_k + social_k + price25 + C(quarter) - 1", data=demeaned
).fit()
# 3) linearmodels, with shop and quarter effects
fe = PanelOLS(panel["transactions"], panel[X],
entity_effects=True, time_effects=True).fit()
print(pd.DataFrame({"dummies": fe_dummies.params[X],
"within": fe_within.params[X],
"PanelOLS": fe.params}).round(1))
# dummies within PanelOLS
# email_k 379.1 379.1 379.1
# social_k 200.3 200.3 200.3
# price25 -493.2 -493.2 -493.2
All three say the same: 379 for the newsletter against a true 380, 200 for paid social against 210, and minus 493 for price against minus 440. Price is the least accurate of the three, exactly as the within share warned.
The coefficients agree, the standard errors do not quite. The hand made within version reports 39, 57 and 117, the other two report 41, 59 and 123. The hand made version does not know it has spent five degrees of freedom on the shop means, so its error margins are slightly too narrow. That is the best reason to use the dummies or PanelOLS in practice, and to treat the hand made version as the explanation.
Which of the two? I reach for the dummy version when I want the shop effects as named numbers to hand to the owner, and for PanelOLS when there are hundreds of units, because it never builds the dummy columns. Both are fine for five shops.
Example: what happens when you forget the time effects
Look back at the "right" line in the swapped index example: 111, 776 and 228. That was shop effects only, no quarter effects. Every shop grew its newsletter and its paid social over the three years, and every shop's trade drifted up a little at the same time. Without quarter effects, the model hands that shared drift to whichever driver grew fastest, here paid social, and the paid social effect comes out at almost four times the truth. With time_effects=True it drops back to 200. If a chain wide trend, a price rise across the board or a national campaign moved every shop at once, the quarter effects are what keep it out of your marketing numbers.
Random effects, and why linearmodels quietly gave up
Random effects keeps a shop level term but treats it as a random draw with variance rather than as five numbers to estimate. It then removes only part of each shop's average, a share :
where is the variance of the quarter to quarter noise, the variance of the shop levels, and the number of quarters per shop. With you get pooled OLS back, with you get fixed effects. It is the more efficient estimator when the shop levels are unrelated to the marketing, and a biased one when they are not, as the Marketing Analytics chapter explains. Variance, the square of the standard deviation, is in Foundations: spread.
Example: random effects with five shops
time_dummies = pd.get_dummies(panel.index.get_level_values("qdate"),
prefix="q", drop_first=True, dtype=float)
time_dummies.index = panel.index
exog = pd.concat([panel[X], time_dummies], axis=1).assign(const=1.0)
re_lm = RandomEffects(panel["transactions"], exog).fit()
print(re_lm.theta.iloc[0, 0]) # 0.0
print(re_lm.params[X].round(0).to_dict())
# {'email_k': 698.0, 'social_k': 81.0, 'price25': 182.0} identical to pooled OLS
A theta of exactly zero, and coefficients identical to the pooled regression. Nothing crashed and no warning appeared. This is the second trap of the chapter, and it comes from having few units. linearmodels estimates from a regression of the five shop averages on all the regressors.5 With three drivers, eleven quarter dummies and a constant, that is fifteen columns for five averages. The regression fits perfectly, the estimated shop variance comes out at or below zero, it is set to zero, and random effects collapses into pooled OLS. It happens whenever the regressors outnumber the units. In a panel of 200 client accounts you would not see it. In a chain of five shops you will, as long as you keep the time effects, and you must keep them.
The way out is to estimate the same random intercept model by restricted maximum likelihood (REML), a method that estimates the variances directly instead of from those five averages. statsmodels does that with mixedlm, its linear mixed effects model.6
with warnings.catch_warnings():
warnings.simplefilter("ignore") # small samples trigger convergence notes
re = smf.mixedlm("transactions ~ email_k + social_k + price25 + C(quarter)",
data=df, groups=df["shop"]).fit(reml=True)
print(re.params[X].round(0))
# email_k 388.0
# social_k 206.0
# price25 -462.0
sigma_u2, sigma_e2 = float(re.cov_re.iloc[0, 0]), re.scale
theta = 1 - np.sqrt(sigma_e2 / (12 * sigma_u2 + sigma_e2))
print(round(np.sqrt(sigma_u2)), round(np.sqrt(sigma_e2)), round(theta, 3))
# 4243 502 0.966
Random effects now sits where theory says it should, between pooled and fixed effects, and very close to fixed effects: 388, 206 and minus 462. The reason is in the theta of 0.966. The shops differ by about 4,200 transactions a quarter (the standard deviation of their levels), while the quarter to quarter noise is about 500. When units differ that much, random effects removes almost the whole shop average and behaves almost like fixed effects. Here that happens to help. It does not prove random effects is valid. That is the next section.
Is random effects allowed? The Hausman test by hand, and why it failed
The Hausman idea from the Marketing Analytics chapter: estimate both, and if the coefficients differ by more than sampling noise allows, the random effects assumption has failed.7 Neither linearmodels 7.0 nor statsmodels 0.14 has a function for it, so you compute it from the formula:
where and are the three fixed and random effects coefficients, is each estimator's covariance matrix, the prime turns the difference into a row and the power is the matrix inverse. Under the null hypothesis that random effects is fine, follows a chi squared distribution with 3 degrees of freedom. Test statistics and p values are in Foundations: hypothesis tests, the matrix algebra in Foundations: matrices.
Example: a Hausman statistic that comes out negative
b_fe, b_re = fe.params[X], re.params[X]
V = fe.cov.loc[X, X] - re.cov_params().loc[X, X]
diff = b_fe - b_re
H = float(diff @ np.linalg.inv(V) @ diff)
print(round(H, 2)) # -3.25
print(np.linalg.eigvalsh(V).round(1)) # [-352.8 -8.9 -7.5]
A chi squared statistic cannot be negative, yet here it is. The difference of the two covariance matrices should be positive definite (all its eigenvalues positive), and here all three are negative. The two models estimate the noise variance separately, and in a small sample the random effects covariance can come out larger than the fixed effects one. Stata's own manual calls a negative result "not an unusual outcome" and says the data then fail the asymptotic assumptions of the test.8 It is not evidence for random effects. It is a test that cannot be used here.
The test that works with few shops: Mundlak
There is a regression version of the same question that never goes negative, due to Yair Mundlak.9 Add each shop's average of every driver to the regression. If those averages carry information beyond the drivers themselves, the shop level is related to the marketing, and random effects is not allowed. Formally:
where , and are shop 's averages over the twelve quarters and to measure how much the "between shops" relationship differs from the "within shop" one. The test is whether all three are zero, an ordinary F test from Foundations: hypothesis tests. A bonus: the in this regression are exactly the fixed effects estimates. Wooldridge's textbook presents this regression form of the Hausman test and shows how to make it robust.10
Example: the Mundlak test on the five shops
for col in X:
df[col + "_mean"] = df.groupby("shop")[col].transform("mean")
mundlak = smf.ols(
"transactions ~ email_k + social_k + price25"
" + email_k_mean + social_k_mean + price25_mean + C(quarter)",
data=df,
).fit()
print(mundlak.params[X].round(0).to_dict())
# {'email_k': 379.0, 'social_k': 200.0, 'price25': -493.0} the fixed effects again
print(mundlak.wald_test("email_k_mean = 0, social_k_mean = 0, price25_mean = 0",
scalar=True))
# <F test: F=18.98..., p=6.2...e-08, df_denom=42, df_num=3>
An F statistic of 19.0 on 3 and 42 degrees of freedom, with a p value far below 0.001. The shop averages matter a great deal: shops that send more newsletters on average are bigger for other reasons too. Random effects is ruled out, and fixed effects stay, the same verdict the Marketing Analytics chapter reaches. You can also run this test with clustered standard errors, which is its advantage over the classic Hausman. With five shops the clustered version is no more trustworthy than the clustered errors themselves, which is the next problem.
Clustered standard errors, and what five shops can bear
The twelve quarters of one shop share whatever the model misses about that shop, so they are not twelve independent observations. Clustered standard errors allow for that by letting the residuals within a shop be correlated.11 In linearmodels it is one argument, in statsmodels the cluster ids must be integers.12
Example: conventional against clustered errors
fe_cl = PanelOLS(panel["transactions"], panel[X],
entity_effects=True, time_effects=True
).fit(cov_type="clustered", cluster_entity=True)
print(pd.DataFrame({"conventional": fe.std_errors,
"clustered": fe_cl.std_errors}).round(0))
# conventional clustered
# email_k 41.0 29.0
# social_k 59.0 44.0
# price25 123.0 64.0
The clustered errors came out smaller, not larger. The Marketing Analytics chapter shows them growing by about 45%, which is what you would expect when residuals are correlated within a shop. Here they shrank, and the price error almost halved. That is not good news. A clustered standard error is itself estimated from the clusters, and with five clusters it is estimated from five numbers. Cameron and Miller show that with few clusters these errors tend to be too small, and that "few" can mean anything under 20 to 50.11 Five shops is few by any reading. The honest response is a method built for few clusters.
Example: the wild cluster bootstrap, all 32 ways
The wild cluster bootstrap asks: if the newsletter had no effect, how unusual would the real result be?13 It fits the model with the effect forced to zero, then builds fake datasets by flipping the sign of each shop's residuals, all of one shop together, refits, and compares. With five shops there are exactly ways to flip the signs, so instead of drawing at random you can try all of them.
shop_codes = pd.factorize(df["shop"])[0] # cluster ids must be integers
def wild_cluster_p(data, coef, formula, groups):
"""Two sided p value for one coefficient, every sign pattern of the clusters."""
full = smf.ols(formula, data=data).fit(cov_type="cluster", cov_kwds={"groups": groups})
t_obs = full.tvalues[coef]
null = smf.ols(formula.replace(f"{coef} + ", ""), data=data).fit() # effect forced to 0
clusters = np.unique(groups)
t_star = []
for signs in itertools.product([-1, 1], repeat=len(clusters)):
w = np.array(signs)[np.searchsorted(clusters, groups)]
fake = data.assign(transactions=null.fittedvalues + w * null.resid)
refit = smf.ols(formula, data=fake).fit(cov_type="cluster", cov_kwds={"groups": groups})
t_star.append(refit.tvalues[coef])
return t_obs, np.mean(np.abs(t_star) >= abs(t_obs) - 1e-9)
for c in X:
t_obs, p = wild_cluster_p(df, c, formula, shop_codes)
print(f"{c:9} t = {t_obs:6.2f} wild bootstrap p = {p:.4f}")
# email_k t = 11.88 wild bootstrap p = 0.0625
# social_k t = 4.13 wild bootstrap p = 0.0625
# price25 t = -6.92 wild bootstrap p = 0.0625
All three p values are 0.0625, and that is not a coincidence. Flipping every sign gives the same absolute t value as flipping none, so the 32 patterns produce at most 16 different results. And the pattern "flip nothing" always reproduces the real data, so at least two of the 32 are as extreme as the real result. The smallest p value five shops can ever produce is . A newsletter effect almost twelve standard errors from zero cannot reach the usual 0.05 threshold.
That is the most useful sentence in this chapter for anyone who reads significance stars: with five units, no method designed for few clusters can call anything significant at 5%. You can still act on the estimates. The true effects are there, and the fixed effects found them. But the confidence comes from the size and stability of the effect, from the checks below and from an experiment, not from a star. Sample size is in Foundations: sample size, and what an error margin means in Foundations: confidence intervals.
What the coefficients are worth in pounds
Fixed effects estimates are only useful once they are turned into money and into an elasticity. The Marketing Analytics example assumes an average transaction of €16 across the chain.
Example: from coefficients to pounds and an elasticity
- Newsletter: of sales per thousand extra sends. The pooled number would have said , nearly twice as much.
- Paid social: of sales per extra €1,000. Before margin, that pays back about three times. Pooled it looked like €1,296.
- Price: losing 493 transactions on an average of 18,590 per shop and quarter is . A 25 cent rise on an average item price of €3.99 is . The elasticity at the mean is , see Foundations: price elasticity.
An elasticity of minus 0.42 means demand is inelastic: a 1% price rise loses about 0.42% of transactions, so revenue still rises, by less than the price. The chapter on price elasticity with regression in Python goes deeper, and percentage changes are in Foundations: percentages.
Each group is one driver, each bar one estimator, the first bar the truth built into the data. The pooled bars are the odd ones out in every group. The fixed and random effects bars sit next to the truth.
What the shop effects and residuals say about Bishopstown
The shop effects are the second deliverable, and the residuals the third. A shop effect says how much trade a shop does at the chain's average marketing and prices: its level. A residual says how far a quarter fell from what the shop's own level, the quarter and its own marketing predicted: its trend.
Example: levels per square metre and the 2025 residuals
df["resid"] = fe_dummies.resid
avg = df[X].mean()
levels = {}
for name, rows_ in df.groupby("shop"):
at_average = rows_.assign(**avg.to_dict()) # same shop, chain average marketing and price
levels[name] = fe_dummies.predict(at_average).mean()
table = pd.DataFrame({"level": pd.Series(levels).round(-2)})
table["per_m2"] = (table["level"] / shops.set_index("shop")["floor_m2"]).round(1)
table["resid_2025"] = (df[df["qdate"].dt.year == 2025]
.groupby("shop")["resid"].sum().round(-1))
print(table)
| Shop | Floor space | Level (transactions per quarter) | Per square metre | Sum of 2025 residuals |
|---|---|---|---|---|
| Douglas | 360 m² | 26,000 | 72.2 | plus 1,240 |
| Knocknacarra | 240 m² | 18,200 | 75.8 | plus 1,080 |
| Bishopstown | 225 m² | 18,000 | 80.0 | minus 2,590 |
| Renmore | 190 m² | 16,200 | 85.3 | minus 880 |
| Blackrock | 170 m² | 14,600 | 85.9 | plus 1,150 |
Per square metre, Bishopstown is third of five, right in the middle. It is not a bad shop. But its 2025 residuals add up to minus 2,590 transactions, the worst of the five. Something changed there.
The trap in the residuals: the drop is partly hidden
The residuals above come from a model fitted on all twelve quarters, including the four bad ones. That model has quietly lowered Bishopstown's level to fit them, which makes 2025 look less bad and 2023 to 2024 look better than they were. You can see it in Bishopstown's residuals before the drop: 520, 510, 330, 300, minus 100, 100, 680, 230. Seven of eight are positive. Residuals of an honest model should wander either side of zero.
The fix is the same idea as a holdout in forecasting. Fit the model without the suspect quarters, let the other four shops set the 2025 quarter effects, and predict what Bishopstown should have done.
Example: Bishopstown's gap from a model that never saw 2025 at Bishopstown
suspect = (df["shop"] == "Bishopstown") & (df["qdate"].dt.year == 2025)
fe_train = smf.ols(formula, data=df[~suspect]).fit()
gap = df.loc[suspect, "transactions"] - fe_train.predict(df[suspect])
print(gap.round(-1).tolist(), round(gap.sum(), -1))
# [-1800.0, -770.0, -1640.0, -690.0] -4900.0
The gap is minus 4,900 transactions, almost twice the minus 2,590 the in sample residuals suggested. The true cut built into the data was 6,000. The holdout gets much closer. The rest of the difference is noise. At the Marketing Analytics chapter's average Bishopstown transaction of €14.50, that is of sales missing in 2025, against about €37,600 from the in sample residuals.
Each pair of bars is one quarter of 2025. The holdout bar is the longer one in every quarter: the model that was allowed to see the bad quarters had already explained part of them away.
My rule: when you suspect a break at one unit, never judge it by residuals from a model that includes the break. Leave the suspect periods out, predict them, and report the gap. It takes three lines and it roughly doubles what you find here.
Like for like sales in pandas
Like for like sales compare only the shops that traded in both periods, so a new shop does not flatter growth.14 The formula, as in the Marketing Analytics chapter:
where is like for like growth in quarter , is the set of shops that traded in both quarters, is sales at shop in quarter , and is the same quarter a year earlier, so the season cancels. Year on year comparisons are in Foundations: seasonality.
Example: Mervue opens and the headline doubles
Say a sixth shop opens in Mervue in Galway in spring 2025, as in the Marketing Analytics chapter, with 9,800 transactions in the third quarter.
mervue = pd.DataFrame({"shop": "Mervue", "quarter": ["2025Q2", "2025Q3", "2025Q4"],
"transactions": [7400, 9800, 8900]})
sales = pd.concat([df[["shop", "quarter", "transactions"]], mervue], ignore_index=True)
def like_for_like(sales, this_q, last_q):
now = sales[sales["quarter"] == this_q].set_index("shop")["transactions"]
before = sales[sales["quarter"] == last_q].set_index("shop")["transactions"]
comparable = now.index.intersection(before.index) # traded in both quarters
total = now.sum() / before.sum() - 1
lfl = now[comparable].sum() / before[comparable].sum() - 1
return round(float(total), 3), round(float(lfl), 3)
print(like_for_like(sales, "2025Q3", "2024Q3")) # (0.112, 0.024)
Total growth, counting Mervue: . Like for like, the five comparable shops only: . The headline says the chain grew by a ninth. The estate it already had grew by a fortieth, with Bishopstown pulling it down.
The comparable set is decided by the data here, through intersection. In a real business, decide the rule first and write it down (for example "traded every day of both quarters, no refit"), then compute. Choosing afterwards which shops count is how like for like numbers get flattered.
The lead test: is marketing following sales?
Fixed effects remove differences between shops. They do nothing if the shop managers spend more on marketing because they expect a good quarter. A quick check from the Marketing Analytics chapter: add next quarter's spend to this quarter's model. Future spend cannot cause today's sales, so if it "predicts" them, causation runs backwards.
Example: next quarter's newsletters
df["email_next"] = df.groupby("shop")["email_k"].shift(-1) # next quarter, same shop
lead_data = df.dropna(subset=["email_next"])
lead = smf.ols(
"transactions ~ email_k + email_next + social_k + price25 + C(shop) + C(quarter)",
data=lead_data,
).fit(cov_type="cluster", cov_kwds={"groups": pd.factorize(lead_data["shop"])[0]})
print(lead.params[["email_k", "email_next"]].round(0).to_dict())
# {'email_k': 382.0, 'email_next': -43.0}
print(round(lead.pvalues["email_next"], 2)) # 0.54
Next quarter's newsletters have a coefficient of minus 43, small and nowhere near significant (p of 0.54, and remember the clustered p values are too optimistic with five shops, so the real evidence is weaker still). This quarter's effect stays at 382. No sign that marketing is chasing sales. The shift(-1) within groupby matters: shifting the whole column would hand Douglas's first quarter to Renmore's last. Time handling in pandas is in time series in pandas. When the lead test does fail, the fix is an instrument or an experiment, which come in later chapters of this series on simultaneous equations and on A/B tests.
Three export traps that quietly break a panel
The models above are the easy part. The panel is only as good as the table it is built from, and business exports have habits.
| Trap | What it does to the panel | The fix in pandas |
|---|---|---|
| Order times in UTC | Late orders on the last evening of a quarter land in the wrong quarter | tz_convert to the shop's time zone before to_period("Q") |
| Refunds as separate rows, dated when refunded | A December sale refunded in January lowers the next quarter | Assign each refund to the quarter of its original order |
| Chain wide spend split equally | Every shop gets the same "spend", which has no within variation that means anything | Keep chain campaigns out of the shop drivers; the quarter effects absorb them |
Example: the quarter boundary in UTC
The till export stores order times in UTC. On 30 June 2025 Ireland is on Irish Standard Time, an hour ahead.
orders = pd.DataFrame({
"order_id": [1041, 1042, 1043],
"created_at": ["2025-06-30T22:40:00Z", "2025-06-30T23:15:00Z", "2025-07-01T08:05:00Z"],
})
orders["created_at"] = pd.to_datetime(orders["created_at"], utc=True)
orders["quarter_utc"] = orders["created_at"].dt.tz_localize(None).dt.to_period("Q")
local = orders["created_at"].dt.tz_convert("Europe/Dublin")
orders["quarter_local"] = local.dt.tz_localize(None).dt.to_period("Q")
print(orders[["order_id", "quarter_utc", "quarter_local"]])
# order_id quarter_utc quarter_local
# 0 1041 2025Q2 2025Q2
# 1 1042 2025Q2 2025Q3
# 2 1043 2025Q3 2025Q3
Order 1042 was placed at a quarter past midnight on 1 July in Cork, which is the third quarter, but in UTC it is still 30 June. One order is nothing. A late night promotion on the last evening of a quarter, repeated every quarter, moves a good few hundred transactions across the boundary each time, and the quarter effects cannot absorb it if only the shops that ran the promotion are affected. Convert first, then group.
The decision path, in one picture
Read it top to bottom. The highlighted path is the one Heron Pantry takes: enough movement within the shops, a clear Mundlak result, fixed effects, honest errors, then the shop levels and the holdout gap.
The whole chain at a glance
One more chart, because it is the one to show Niamh first. It is the picture behind every number above.
The horizontal axis is the quarter, the vertical axis till transactions. The lines sit one above the other like shelves, and those gaps are the shop effects. The summer peak repeats every year, and that is the quarter effect. What marketing has to explain is the small wiggle left inside each line, which is why the within share matters so much. The data storytelling chapter on showing time, trends and seasonality explains how to draw this so the season does not hide the trend, and the chapter on charts in Python with matplotlib, seaborn and plotly shows the code.
My view
My view: for a business with between five and fifty units, two way fixed effects is the default, and random effects has to earn its place through a Mundlak test, not through a Hausman statistic that may come out negative. I would never put a significance star on anything estimated from five units. I would report the estimate, the wild cluster bootstrap's honest floor of 0.0625, the within share, and the holdout gap, and let the size and stability of the effect carry the argument.
I would also build the whole thing as a script with the checks in it (unique index, entities equal to the number of shops, time effects on), not as a notebook someone clicks through. The chapter on a reproducible Python analysis workflow shows how to turn those checks into tests. Every trap in this chapter, the swapped index, the collapsed random effects, the shrinking clustered errors, ran without an error message. Only a check catches them.
Turning panels like this into decisions is part of my Data Science work, alongside the dashboards and the storytelling that carry them to the people who decide. The code, the accounts and the data stay yours.
Conclusion
Panel regression in Python is a few lines once the table is right. A long DataFrame, a MultiIndex with the shop first, PanelOLS with shop and quarter effects, and you have the fixed effects. The work, and the value, sits around those lines. Measure the within share before you fit. Print the number of entities. Keep the time effects. Do not trust a random effects model that linearmodels has silently turned into pooled OLS, or a Hausman statistic below zero: run the Mundlak test instead. With five shops, accept that no p value will fall below 0.0625, and say so. And judge a shop that broke by a model that never saw the break.
At Heron Pantry that turns "the newsletter is worth 698 transactions and price rises sell more" into "the newsletter is worth about 380, price costs sales at an elasticity near minus 0.4, and Bishopstown has lost roughly €71,000 of sales against its own history since January". The next chapter in this series takes the time dimension on its own and forecasts demand with autocorrelation and seasonality.
