Tableau de statistiques descriptives

Le « tableau 1 » d'un article empirique — N, moyenne, écart type, min, médiane et max par variable, en panneaux, avec les moyennes par groupe et un test de leur différence.

Tableau de statistiques descriptives

Avant tout modèle, un article décrit ses données. Ce tableau donne, pour chaque variable, le nombre d'observations non manquantes, la moyenne, l'écart type, le minimum, la médiane et le maximum, regroupés en panneaux (variable expliquée, caractéristiques individuelles, réseaux). Le bloc de droite compare les deux groupes qui sont l'objet de l'article — ici les répondants qui comptent rester et ceux qui comptent partir — avec la différence des moyennes et des étoiles issues d'un test t de Welch, comme dans un tableau d'équilibre.

Toute la mise en forme est faite par Great Tables plutôt qu'avec des chaînes Python : fmt_integer() et fmt_number() (avec drop_trailing_zeros pour que les variables 0/1 affichent 0 et 1), cols_merge() pour accoler les étoiles à la différence, sub_missing() pour laisser des cellules vides, des panneaux tab_stub() tirés d'une colonne de groupe avec tab_stub_indent(), et gtsave(), la façon actuelle d'exporter un PNG (elle remplace save(), fondée sur Selenium). Le rendu reprend celui du tableau de régression de cette famille : police à empattements, titre en petites capitales et filets horizontaux seulement.

Le contexte est celui de Blakely & Warin (2012, Global Economy Journal) : choix ou mimétisme dans la décision d'émigrer en Europe. Les données sont simulées à des fins d'illustration — ce ne sont ni les données ni les résultats de l'article : 2 500 répondants à une enquête, dont environ 6 % n'ont pas déclaré le revenu du ménage, si bien que N varie d'une ligne à l'autre.

Le code et le texte à l'intérieur des figures sont en anglais.

summary-statistics.py · 94 lignes
Télécharger GitHub
import numpy as np
import pandas as pd
from scipy import stats
from great_tables import GT, loc, style
# Simulated data, set in the context of Blakely & Warin (2012) [blakely2012]

# Data: 2,500 respondents; younger, unemployed and better-connected people plan to move
rng = np.random.default_rng(2012)
n = 2500
age = rng.uniform(18, 70, n).round()
tertiary = rng.binomial(1, 0.3, n)
unemployed = rng.binomial(1, 0.1, n)
network = rng.binomial(1, 0.35, n)
contacts = rng.poisson(0.6 + 2.2 * network)
satisfaction = rng.integers(1, 11, n)
income = np.exp(rng.normal(3.3 + 0.35 * tertiary - 0.4 * unemployed, 0.45, n)).round(1)
income[rng.random(n) < 0.06] = np.nan                     # item non-response
eta = -0.2 - 0.045 * age + 0.35 * tertiary + 0.7 * unemployed + 0.95 * network - 0.12 * satisfaction
move = rng.binomial(1, 1 / (1 + np.exp(-eta)))
df = pd.DataFrame({"move": move, "age": age, "female": rng.binomial(1, 0.52, n),
                   "tertiary": tertiary, "unemployed": unemployed, "income": income,
                   "satisfaction": satisfaction, "network": network, "contacts": contacts})

panels = {
    "Panel A. Outcome": {"move": "Intends to move abroad (0/1)"},
    "Panel B. Individual characteristics": {
        "age": "Age (years)", "female": "Female (0/1)", "tertiary": "Tertiary education (0/1)",
        "unemployed": "Unemployed (0/1)", "income": "Household income (€ thousand per year)",
        "satisfaction": "Life satisfaction (1–10)"},
    "Panel C. Networks": {
        "network": "Family or friends abroad (0/1)", "contacts": "Contacts abroad (number)"},
}

# One row per variable: full-sample statistics, then group means and Welch t-test
rows = []
for panel, variables in panels.items():
    for var, label in variables.items():
        x = df[var].dropna()
        row = {"panel": panel, "variable": label, "N": len(x), "mean": x.mean(), "sd": x.std(),
               "min": x.min(), "median": x.median(), "max": x.max()}
        if var != "move":                                   # the outcome defines the groups
            stay, go = x[df.move == 0], x[df.move == 1]
            t = stats.ttest_ind(go, stay, equal_var=False)
            row |= {"stay": stay.mean(), "go": go.mean(), "diff": go.mean() - stay.mean(),
                    "stars": "***" if t.pvalue < .01 else "**" if t.pvalue < .05 else "*" if t.pvalue < .1 else ""}
        rows.append(row)
tab = pd.DataFrame(rows)
n_stay, n_go = (df.move == 0).sum(), (df.move == 1).sum()

full = ["N", "mean", "sd", "min", "median", "max"]
groups = ["stay", "go", "diff"]
table = (
    GT(tab)
    .tab_stub(rowname_col="variable", groupname_col="panel")
    .tab_stub_indent(rows=list(range(len(tab))), indent=2)
    .tab_header(title="TABLE II", subtitle="Descriptive statistics")
    .tab_spanner(label="Full sample", columns=full, id="full")
    .tab_spanner(label="Mean by intention", columns=groups, id="groups")
    .cols_label(N="N", mean="Mean", sd="SD", min="Min", median="Median", max="Max",
                stay=f"Stay ({n_stay:,})", go=f"Move ({n_go:,})", diff="Difference")
    .fmt_integer(columns="N")
    .fmt_number(columns=["mean", "sd", "stay", "go", "diff"], decimals=2)
    .fmt_number(columns=["min", "median", "max"], decimals=1, drop_trailing_zeros=True)
    .cols_merge(columns=["diff", "stars"], pattern="<<{0}{1}>>")   # stars glued to the difference
    .sub_missing(columns=groups, missing_text="")
    .cols_align("center", columns=full + groups)
    .tab_source_note(f"Notes: n = {n:,} respondents (simulated). N counts non-missing observations; "
                     f"household income is missing for {df.income.isna().sum()} respondents.")
    .tab_source_note("Difference = Move − Stay, with stars from Welch t-tests of equal means: "
                     "*p < 0.1; **p < 0.05; ***p < 0.01.")
    # Same journal look as Table I: serif type, small-caps title, horizontal rules only
    .opt_table_font(font=["Latin Modern Roman", "Times New Roman", "Georgia", "serif"])
    .tab_options(
        table_width="900px", 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",
        row_group_border_top_style="none", row_group_border_bottom_style="none",
        row_group_padding="6px",
        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="3px", 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.row_groups(), loc.spanner_labels(ids=["full", "groups"])])
)
table.show()

Les figures utilisent le style PyStatlas (facultatif) : ajoutez plt.style.use("pystatlas.mplstyle") pour obtenir exactement le même rendu.

Source des données

  • 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.
  • Blakely & Warin (2012), the decision to migrate in Europe. Blakely, A., & Warin, T. (2012). Choice or mimetism in the decision to migrate? A European illustration. Global Economy Journal, 12(2). https://doi.org/10.1515/1524-5861.1818
    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.

Les exemples illustrent des méthodes statistiques. Leurs chiffres sont simulés, sauf mention contraire dans l'entrée, et leurs titres décrivent ce que chaque figure montre dans ces données simulées — ni les résultats des articles cités, ni la position de l'auteur sur la question de fond. Pour les résultats, le contexte et les données, reportez-vous aux articles cités ici.

Comment citer

PyStatlas est créé et maintenu par Thierry Warin. S'il vous a été utile dans vos travaux, merci de le citer.

Warin, T. (2026). Summary statistics 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/summary-statistics/

@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}
}

Plus dans Tableaux académiques