描述性统计表

实证论文的“表 1”——按面板列出每个变量的 N、均值、标准差、最小值、中位数和最大值,并给出分组均值及其差异检验。

描述性统计表

在建立任何模型之前,论文先描述数据。此表给出每个变量的非缺失观测数、均值、标准差、最小值、中位数和最大值,并按面板分组(结果变量、个人特征、社会网络)。右侧部分比较论文关注的两组——这里是打算留下和打算移居的受访者——给出均值差及 Welch t 检验的星号,如同平衡表。

所有格式都由 Great Tables 本身完成,而不是用 Python 字符串:fmt_integer() 和 fmt_number()(用 drop_trailing_zeros 让 0/1 变量显示为 0 和 1)、用 cols_merge() 把星号接在差值后面、用 sub_missing() 留空单元格、由分组列生成的 tab_stub() 面板及 tab_stub_indent(),以及 gtsave()——当前导出 PNG 的方式(取代基于 Selenium 的 save())。外观与本类别中的回归表一致:衬线字体、小型大写标题,只用横线。

背景是 Blakely & Warin (2012, Global Economy Journal) 关于欧洲移民决定是选择还是模仿的研究。数据为说明用的模拟数据,并非论文的数据或结果:2,500 名调查受访者,其中约 6% 缺失家庭收入,因此各行的 N 不同。

代码及图中文字均为英文。

summary-statistics.py · 94 行
下载 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()

图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。

数据来源

  • 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.

这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。

如何引用

PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。

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

更多学术表格图表