Panel data regression table

Pooled OLS, random effects, country fixed effects and two-way fixed effects side by side, with clustered standard errors, fixed-effect indicators and a Hausman test.

Panel data regression table

The workhorse table of applied economics with country-year data. The same regression is estimated four ways: pooled OLS, which ignores the panel structure; random effects, which treats each country's level as random noise; country fixed effects, which keep only the variation within each country; and two-way fixed effects, which also absorb shocks common to all countries in a year. Standard errors are clustered by country, and the foot of the table says which fixed effects each column includes, how many observations and countries it uses, and its within and overall R².

Comparing the columns is the point. Here institutional quality is higher in countries that attract more FDI for other, permanent reasons, so its pooled and random-effects coefficients are biased upwards; the fixed-effects columns remove that bias. A robust Hausman test rejects random effects in favour of fixed effects: it is the Mundlak version, which adds each regressor's country mean to the random-effects model and tests them jointly with the clustered covariance (the classic Hausman formula can turn negative and ignores clustering). The F-test of poolability rejects the pooled model. As in fixest and Stata, the constant is not reported once fixed effects absorb it.

The setting is Stojkov & Warin (2018, Journal of East-West Business): EU membership and foreign direct investment in transition economies. The data are simulated for illustration — they are not the paper's data or results: 28 economies observed over 18 years, with FDI inflows in % of GDP. The models come from linearmodels (PooledOLS, RandomEffects and PanelOLS with EntityEffects and TimeEffects, fitted with cov_type="clustered", and wald_test() for the Mundlak test); the table is built with Great Tables in the same journal style as the other tables of this family.

panel-regression.py · 131 lines
Download GitHub
import numpy as np
import pandas as pd
from great_tables import GT, html, loc, style
from linearmodels.panel import PanelOLS, PooledOLS, RandomEffects
# Simulated data, set in the context of Stojkov & Warin (2018) [stojkov2018fdi]

# Data: 28 transition economies × 18 years; a permanent country "attractiveness" raises both
# FDI and institutional quality, so pooled estimates of the institutions effect are biased
rng = np.random.default_rng(2018)
n_c, n_t = 28, 18
country = np.repeat([f"C{i:02d}" for i in range(n_c)], n_t)
year = np.tile(np.arange(2000, 2000 + n_t), n_c)
appeal = np.repeat(rng.normal(0, 1.5, n_c), n_t)                         # unobserved country effect
shock = np.tile(rng.normal(0, 0.8, n_t) + np.linspace(-1, 1, n_t), n_c)  # common year shocks
entry = np.repeat(rng.integers(2004, 2025, n_c), n_t)                    # some never join in-sample
df = pd.DataFrame({
    "country": country, "year": year,
    "eu_member": (year >= entry).astype(int),
    "institutions": 0.6 * appeal + 0.04 * (year - 2000) + rng.normal(0, 0.6, n_c * n_t),
    "openness": np.repeat(rng.normal(0, 1, n_c), n_t) + rng.normal(0, 0.5, n_c * n_t),
    "log_gdp": np.repeat(rng.normal(3, 0.8, n_c), n_t) + 0.03 * (year - 2000) + rng.normal(0, 0.1, n_c * n_t),
    "ulc": rng.normal(0, 1, n_c * n_t),
})
df["fdi"] = (2 + 0.5 * df.institutions + 0.6 * df.openness + 1.2 * df.log_gdp - 0.4 * df.ulc
             + 1.5 * df.eu_member + 1.8 * appeal + shock + rng.normal(0, 1.2, n_c * n_t))
panel = df.set_index(["country", "year"])

labels = {"institutions": "Institutional quality", "openness": "Trade openness",
          "log_gdp": "Market size (log GDP)", "ulc": "Unit labour cost", "eu_member": "EU member (0/1)",
          "Intercept": "Constant"}
rhs = " + ".join(list(labels)[:-1])
specs = {
    "Pooled OLS": PooledOLS.from_formula(f"fdi ~ 1 + {rhs}", panel),
    "Random effects": RandomEffects.from_formula(f"fdi ~ 1 + {rhs}", panel),
    "Country FE": PanelOLS.from_formula(f"fdi ~ 1 + {rhs} + EntityEffects", panel),
    "Two-way FE": PanelOLS.from_formula(f"fdi ~ 1 + {rhs} + EntityEffects + TimeEffects", panel),
}
fits = {k: m.fit(cov_type="clustered", cluster_entity=True) for k, m in specs.items()}
cols = [f"({k + 1})" for k in range(len(fits))]

# Robust Hausman test (Mundlak): add each regressor's country mean to the RE model and
# test that the means are jointly zero with the clustered covariance — FE vs. RE
xs = list(labels)[:-1]
means = panel[xs].groupby(level="country").transform("mean").add_prefix("mean_")
mundlak = RandomEffects.from_formula(f"fdi ~ 1 + {rhs} + " + " + ".join(means.columns),
                                     panel.join(means)).fit(cov_type="clustered", cluster_entity=True)
hausman = mundlak.wald_test(formula=[f"{m} = 0" for m in means.columns])
f_pool = fits["Country FE"].f_pooled
fe_cols = {"(3)", "(4)"}                  # the constant is not reported with fixed effects


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("-", "−")


def pval(p):
    return "< 0.001" if p < .001 else f"{p:.3f}"


# Body: coefficient row and standard-error row per term, as in stargazer
rows = []
for term, name in labels.items():
    keep = {c: term in r.params and not (term == "Intercept" and c in fe_cols)
            for c, r in zip(cols, fits.values())}
    coef = {c: num(r.params[term]) + stars(r.pvalues[term]) if keep[c] else ""
            for c, r in zip(cols, fits.values())}
    se = {c: f"({num(r.std_errors[term])})" if keep[c] else "" for c, r in zip(cols, fits.values())}
    rows += [{"term": name, **coef}, {"term": "", **se}]
n_body = len(rows)
coef_rows, se_rows = list(range(0, n_body, 2)), list(range(1, n_body, 2))

# Foot: fixed effects, sample, fit and specification tests
yes_no = lambda flags: dict(zip(cols, ["Yes" if f else "No" for f in flags]))
rows += [
    {"term": "Country fixed effects", **yes_no([0, 0, 1, 1])},
    {"term": "Year fixed effects", **yes_no([0, 0, 0, 1])},
    {"term": "Observations", **{c: f"{r.nobs:,}" for c, r in zip(cols, fits.values())}},
    {"term": "Countries", **{c: f"{r.entity_info['total']:.0f}" for c, r in zip(cols, fits.values())}},
    {"term": "R² (within)", **{c: num(r.rsquared_within) for c, r in zip(cols, fits.values())}},
    {"term": "R² (overall)", **{c: num(r.rsquared_overall) for c, r in zip(cols, fits.values())}},
    {"term": "F-test, no country effects", **dict(zip(cols, ["", "", f"{f_pool.stat:.1f} (p {pval(f_pool.pval)})", ""]))},
    {"term": "Robust Hausman test, FE vs. RE",
     **dict(zip(cols, ["", f"χ²({hausman.df}) = {hausman.stat:.1f} (p {pval(hausman.pval)})", "", ""]))},
]
tab = pd.DataFrame(rows)
n_foot_first = n_body                 # rule above the fixed-effect indicators
n_stats_first = n_body + 2            # thin rule above the sample statistics

table = (
    GT(tab, rowname_col="term")
    .tab_header(title="TABLE IV", subtitle="Institutions, EU membership and FDI: panel estimates")
    .tab_spanner(label="Dependent variable: FDI inflows (% of GDP)", columns=cols, id="dep")
    .cols_label(**{c: html(f"{c}<br>{name}") for c, name in zip(cols, fits)})
    .cols_align("center", columns=cols)
    .cols_width({"term": "210px", **{c: "185px" for c in cols}})
    .tab_source_note(f"Notes: n = {n_c} economies × {n_t} years (simulated). Standard errors clustered by "
                     "country in parentheses. *p < 0.1; **p < 0.05; ***p < 0.01.")
    .tab_source_note("Robust Hausman test: Mundlak regression, Wald test that the country means of the "
                     "regressors are zero. F-test of poolability for (3).")
    # 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"]))
    # standard error tucked under its coefficient
    .tab_style(style.css("padding-bottom: 0;"), [loc.body(rows=coef_rows), loc.stub(rows=coef_rows)])
    .tab_style(style.css("padding-top: 0;"), [loc.body(rows=se_rows), loc.stub(rows=se_rows)])
    # thin rules: above the fixed-effect indicators and above the sample statistics
    .tab_style(style.borders(sides="top", style="solid", weight="1px", color="#000"),
               [loc.body(rows=[n_foot_first, n_stats_first]), loc.stub(rows=[n_foot_first, n_stats_first])])
)
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.
  • Stojkov & Warin (2018), EU membership and FDI. Stojkov, A., & Warin, T. (2018). EU membership and FDI: Is there an endogenous credibility effect? Journal of East-West Business, 24, 144–169. https://doi.org/10.1080/10669868.2018.1431579
    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). Panel data regression 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/panel-regression/

@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