Difference-in-differences table
Staggered adoption estimated four ways — two-way fixed effects, with controls, Gardner's two-stage DiD and Wooldridge's extended TWFE — with a pre-trend test and the true effect for comparison.

Difference-in-differences (DiD) compares how an outcome changes in units that
adopt a treatment with how it changes in units that do not. When units adopt
at different dates and the effect grows over time, the textbook
two-way fixed effects (TWFE) regression is biased: it uses already-treated
units as controls for later adopters, and those "forbidden comparisons" pull
the estimate down. Columns (1) and (2) are TWFE without and with controls.
Column (3) is Gardner's two-stage DiD (did2s), which estimates the fixed
effects on untreated observations only and then regresses the residualised
outcome on treatment; column (4) is Wooldridge's extended TWFE, one
effect per adoption wave × quarter, averaged with treated-observation weights
(standard error by the delta method). Both are robust to heterogeneous effects.
Because the data are simulated, the notes give the true average effect on the treated, so the bias of the TWFE columns is visible. The foot reports a pre-trend test, the check of parallel trends, done the way Borusyak, Jaravel & Spiess recommend: on untreated observations only, dummies for the five quarters before adoption are added to the fixed-effects model and tested jointly. Standard errors are clustered by market.
The setting is Marty & Warin (2025) on algorithmic collusion and antitrust.
The data are simulated for illustration — they are not the paper's data
or results: 150 local retail fuel markets over 24 quarters, where the stations
of 60% of the markets adopt algorithmic pricing software in one of three
waves; the outcome is the retail margin in cents per litre. All four models
come from pyfixest (feols(), did2s(), wald_test()), the Python port of
R's fixest; the table is built with Great Tables in the journal style of
this family.
import numpy as np
import pandas as pd
import pyfixest as pf
from great_tables import GT, html, loc, style
# Simulated data, set in the context of Marty & Warin (2025) [marty2025collusion]
# Data: 150 fuel markets × 24 quarters; three adoption waves (quarters 8, 12, 16) and never-adopters.
# Margins rise after adoption, more so the longer the software runs and for the first wave.
rng = np.random.default_rng(2026)
M, T = 150, 24
wave = rng.choice([8, 12, 16, 0], M, p=[.2, .2, .2, .4]) # 0 = never adopts
df = pd.DataFrame({"market": np.repeat(np.arange(M), T), "quarter": np.tile(np.arange(T), M),
"wave": np.repeat(wave, T)})
df["treat"] = ((df.wave > 0) & (df.quarter >= df.wave)).astype(int)
since = df.quarter - df.wave # quarters since adoption
effect = np.where(df.treat == 1, (0.6 + 0.12 * since) * np.where(df.wave == 8, 1.5, 1.0), 0.0)
df["cost"] = rng.normal(0, 1, M * T) # wholesale cost shock
df["rivals"] = rng.poisson(4, M * T) # competing stations
df["margin"] = (12 + np.repeat(rng.normal(0, 2, M), T) # market level
+ np.tile(np.linspace(0, 1.5, T) + rng.normal(0, .3, T), M) # common quarter shocks
+ 0.8 * df.cost - 0.3 * df.rivals + effect + rng.normal(0, 1, M * T))
true_att = effect[df.treat == 1].mean()
cluster = {"CRV1": "market"}
# (1)–(2) Two-way fixed effects
twfe = pf.feols("margin ~ treat | market + quarter", df, vcov=cluster)
twfe_x = pf.feols("margin ~ treat + cost + rivals | market + quarter", df, vcov=cluster)
# (3) Gardner's two-stage DiD: fixed effects and controls fitted on untreated observations only
gardner = pf.did2s(df, yname="margin", first_stage="~ cost + rivals | market + quarter",
second_stage="~ treat", treatment="treat", cluster="market")
# (4) Wooldridge's extended TWFE: one effect per wave × quarter cell, then the treated-weighted mean
df["cell"] = np.where(df.treat == 1, df.wave.astype(str) + "_" + df.quarter.astype(str), "untreated")
etwfe = pf.feols("margin ~ i(cell, ref='untreated') + cost + rivals | market + quarter", df, vcov=cluster)
share = df[df.treat == 1].cell.value_counts(normalize=True) # treated-observation weights
w = np.array([share.get(c.removeprefix("cell::"), 0.0) for c in etwfe.coef().index])
etwfe_att = float(w @ etwfe.coef())
att_test = etwfe.wald_test(R=w[None, :], distribution="chi2") # H0: w'b = 0
etwfe_se, etwfe_p = abs(etwfe_att) / np.sqrt(att_test.stat), att_test.pvalue # delta-method SE
# Pre-trend test (Borusyak, Jaravel & Spiess): on untreated observations only, add dummies for
# the 5 quarters before adoption to the fixed-effects model and test them jointly
untreated = df[df.treat == 0].copy()
untreated["lead"] = np.where((untreated.wave > 0) & (untreated.quarter - untreated.wave >= -5),
untreated.quarter - untreated.wave, 0)
pre = pf.feols("margin ~ i(lead, ref=0) + cost + rivals | market + quarter", untreated, vcov=cluster)
leads = [i for i, c in enumerate(pre.coef().index) if c.startswith("lead::")]
pretrend = pre.wald_test(R=np.eye(len(pre.coef()))[leads], distribution="chi2")
# Assemble the table: estimate over (SE), as in stargazer
results = [(twfe.coef()["treat"], twfe.se()["treat"], twfe.pvalue()["treat"]),
(twfe_x.coef()["treat"], twfe_x.se()["treat"], twfe_x.pvalue()["treat"]),
(gardner.coef()["treat"], gardner.se()["treat"], gardner.pvalue()["treat"]),
(etwfe_att, etwfe_se, etwfe_p)]
cols = ["(1)", "(2)", "(3)", "(4)"]
names = ["TWFE", "TWFE", "Two-stage DiD", "Extended TWFE"]
def stars(p):
return "***" if p < .01 else "**" if p < .05 else "*" if p < .1 else ""
def num(x, d=3): # typographic minus sign, as in print
return f"{x:.{d}f}".replace("-", "−")
pre_mean = df.loc[(df.wave > 0) & (df.treat == 0), "margin"].mean()
row = lambda term, values: {"term": term, **dict(zip(cols, values))}
rows = [
row("Algorithmic pricing (ATT)", [num(e) + stars(p) for e, _, p in results]),
row("", [f"({num(s)})" for _, s, _ in results]),
row("Controls (cost, rival stations)", ["No", "Yes", "Yes", "Yes"]),
row("Market fixed effects", ["Yes"] * 4),
row("Quarter fixed effects", ["Yes"] * 4),
row("Robust to heterogeneous effects", ["No", "No", "Yes", "Yes"]),
row("Observations", [f"{len(df):,}"] * 4),
row("Markets (adopting)", [f"{M} ({(wave > 0).sum()})"] * 4),
row("Pre-adoption mean of margin", [num(pre_mean, 2)] * 4),
row("Pre-trend test, leads = 0",
["", "", f"χ²({pretrend.df1}) = {pretrend.stat:.1f} (p = {pretrend.pvalue:.2f})", ""]),
]
tab = pd.DataFrame(rows)
table = (
GT(tab, rowname_col="term")
.tab_header(title="TABLE V", subtitle="Algorithmic pricing and retail margins: difference-in-differences")
.tab_spanner(label="Dependent variable: retail margin (cents per litre)", columns=cols, id="dep")
.cols_label(**{c: html(f"{c}<br>{n}") for c, n in zip(cols, names)})
.cols_align("center", columns=cols)
.cols_width({"term": "260px", **{c: "170px" for c in cols}})
.tab_source_note(f"Notes: {M} markets × {T} quarters (simulated); adoption in three waves. Standard errors "
"clustered by market in parentheses. *p < 0.1; **p < 0.05; ***p < 0.01.")
.tab_source_note(f"True average effect on the treated in the simulation: {true_att:.3f}. "
"Pre-trend test: Wald test of 5 pre-adoption leads, untreated observations only.")
# Same journal look as the other tables: serif type, small-caps title, horizontal rules only
.opt_table_font(font=["Latin Modern Roman", "Times New Roman", "Georgia", "serif"])
.tab_options(
table_width="960px", table_font_size="15px", table_font_color="#000",
heading_title_font_size="15px", heading_subtitle_font_size="15px", heading_padding="1px",
table_border_top_style="hidden", table_border_bottom_style="hidden",
heading_border_bottom_style="none",
column_labels_border_top_style="solid", column_labels_border_top_width="1.5px", # top rule
column_labels_border_top_color="#000",
column_labels_border_bottom_style="solid", column_labels_border_bottom_width="1px",
column_labels_border_bottom_color="#000",
table_body_border_top_style="solid", table_body_border_top_width="1px",
table_body_border_top_color="#000",
table_body_hlines_style="none", stub_border_style="none",
table_body_border_bottom_style="solid", table_body_border_bottom_width="1.5px",
table_body_border_bottom_color="#000",
data_row_padding="4px", source_notes_font_size="13px", source_notes_padding="1px",
)
.tab_style(style.css("font-variant: small-caps; padding-bottom: 8px;"), loc.subtitle())
.tab_style(style.text(style="italic"), loc.spanner_labels(ids=["dep"]))
.tab_style(style.css("padding-bottom: 0;"), [loc.body(rows=[0]), loc.stub(rows=[0])])
.tab_style(style.css("padding-top: 0;"), [loc.body(rows=[1]), loc.stub(rows=[1])])
# thin rules above the specification rows and above the sample statistics
.tab_style(style.borders(sides="top", style="solid", weight="1px", color="#000"),
[loc.body(rows=[2, 6]), loc.stub(rows=[2, 6])])
)
table.show()
Figures use the optional PyStatlas style: add plt.style.use("pystatlas.mplstyle") to match the look exactly.
Data source
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Marty & Warin (2025), algorithmic collusion and antitrust. Marty, F., & Warin, T. (2025). Deciphering algorithmic collusion: Insights from bandit algorithms and implications for antitrust enforcement. Journal of Economy and Technology, 3, 34–43. https://doi.org/10.1016/j.ject.2024.10.001
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
The examples illustrate statistical methods. Their numbers are simulated unless an entry says otherwise, and their titles describe what each figure shows in these simulated data — not findings of the cited papers, nor the author's position on the substantive question. For results, context and data, rely on the papers cited here.
How to cite
PyStatlas is created and maintained by Thierry Warin. If it helped your work, please cite it.
Warin, T. (2026). Difference-in-differences table. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/academic-tables/difference-in-differences/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}More in Academic tables
Regression table, stargazer style
Three nested OLS models side by side, with standard errors under the coefficients and fit statistics at the foot, typeset like a journal table.
stargazer::stargazer(type = "html")Summary statistics table
The "Table 1" of an empirical paper — N, mean, SD, min, median and max per variable in panels, with group means and a test of their difference.
modelsummary::datasummary_balance()Machine learning model comparison table
Five classifiers compared on repeated cross-validation — discrimination, classification and calibration metrics as mean (SD), best in bold, with corrected tests of the AUC gap.
tidymodels::workflow_map() + collect_metrics()