Skip to content

ADescribe · describe.categorical

Frequencies (categorical variables)

How are the values of one or more categorical variables distributed?

Counts, % of rows, valid % and cumulative % per level, with a confidence interval for each proportion (Wilson by default; Clopper–Pearson, Jeffreys, Agresti–Coull or Wald) and optional Goodman simultaneous intervals; the most common level, entropy and imbalance per variable.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Survey wilson”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

FrequenciesRecorded · Python and R agreeRecorded 2026-11-09 · 79 values compared
R

smoke: 4 categories; most common Never (80.1% of valid values), 1 missing.

Rows
237
Variables
3

Plots

smokeHow often does each category occur?
View data
smoke
Never
Regul
Occas
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Occas
Never
Heavy
Never
Regul
Occas
Never
Never
Never
Occas
Never
Never
Never
Never
Never
Never
Regul
Never
Occas
Never
Never
Never
Never
Never
Regul
Never
Never
Never
Never
Occas

First 60 of 236 rows.

Frequencies

VariableLeveln% of rowsValid %Cumulative %95% CI low95% CI high
smokeNever18979.7%80.1%80.1%74.5%84.7%
smokeOccas198.0%8.1%88.1%5.2%12.2%
smokeRegul177.2%7.2%95.3%4.5%11.2%
smokeHeavy114.6%4.7%100.0%2.6%8.2%
smoke(missing)10.4%————
exerciseNone2410.1%10.1%10.1%6.9%14.6%
exerciseSome9841.4%41.4%51.5%35.3%47.7%
exerciseFreq11548.5%48.5%100.0%42.2%54.9%
sexFemale11849.8%50.0%50.0%43.7%56.3%
sexMale11849.8%50.0%100.0%43.7%56.3%
sex(missing)10.4%————

Valid % and intervals exclude missing values; Wilson 95% intervals.

Summary by variable

VariableLevelsValidMissingMost commonIts shareEntropy (bits)Imbalance
smoke42361Never80.1%1.0290.4856
exercise32370Freq48.5%1.3680.1371
sex22361Female50.0%10
  • Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates.
Python

smoke: 4 categories; most common Never (80.1% of valid values), 1 missing.

Rows
237
Variables
3

To keep this page light, the plots are shown once, under the R tab.

Frequencies

VariableLeveln% of rowsValid %Cumulative %95% CI low95% CI high
smokeNever18979.7%80.1%80.1%74.5%84.7%
smokeOccas198.0%8.1%88.1%5.2%12.2%
smokeRegul177.2%7.2%95.3%4.5%11.2%
smokeHeavy114.6%4.7%100.0%2.6%8.2%
smoke(missing)10.4%————
exerciseNone2410.1%10.1%10.1%6.9%14.6%
exerciseSome9841.4%41.4%51.5%35.3%47.7%
exerciseFreq11548.5%48.5%100.0%42.2%54.9%
sexFemale11849.8%50.0%50.0%43.7%56.3%
sexMale11849.8%50.0%100.0%43.7%56.3%
sex(missing)10.4%————

Valid % and intervals exclude missing values; Wilson 95% intervals.

Summary by variable

VariableLevelsValidMissingMost commonIts shareEntropy (bits)Imbalance
smoke42361Never80.1%1.0290.4856
exercise32370Freq48.5%1.3680.1371
sex22361Female50.0%10
  • Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Survey wilsons1_survey · variables: smoke, exercise, sex
  • Clopper simultaneouss1_survey · variables: clap, fold
  • Jeffreys booleanmtcars · variables: manual, cyl_f
  • Agresti hairhair_eye · variables: hair

In the guides

Where it sits in the decision guides

  • Understand data: variables and types · Statistics Guide · Step 0 — Prepare your data
  • Data quality: correct coding · Statistics Guide · Step 0 — Prepare your data
  • Categorical: counts, %, bar chart · Statistics Guide · A — Describe data
  • Descriptive statistics (mean, median, percentiles) · DS & ML Decision Guide · Describe — summarize and visualize
  • Data visualization (histograms, plots) · DS & ML Decision Guide · Describe — summarize and visualize

What you need

Variablescategorical / boolean · 1–10 columns
One or more categorical or yes/no variables.

Choices you make

statistics

Interval methoddefault wilson

Wilson and Jeffreys keep close to the nominal coverage; Wald undercovers for small n or extreme proportions (Brown, Cai & DasGupta 2001).

  • Wilson (recommended)(default) — Inverts the score test; good coverage at any sample size, so it's the usual choice.
  • Clopper–Pearson (exact) — Inverts the exact binomial test; guarantees at least the stated coverage, so it runs wide.
  • Jeffreys — A Bayesian interval with a Jeffreys prior; coverage close to the stated level on average, and good at small n.
  • Agresti–Coull — Adds about two successes and two failures to the Wald interval; easy to compute, and sound except at very small n.
  • Wald (not recommended) — Estimate ± z·SE; coverage is poor at small n or extreme proportions, so use it only to match older work.
Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Simultaneous intervals (Goodman)default off

Intervals that hold for all levels at once — use them when comparing several levels' shares.

options

Order of levelsdefault stored

The stored order is the data dictionary's level order (ordinal scales keep their order).

  • Stored order(default) — Keeps the level order from the data dictionary; right for ordered scales.
  • Most common first — Sorts levels from most to least common; right for unordered categories.

What it reports

n_rows
How many independent units the analysis used; it sets precision and power.
n_variables
How many independent units the analysis used; it sets precision and power.
lead
The first variable listed; the summary sentence describes its categories.
ci_method_label
A range of effect values compatible with your data at the chosen confidence level.

Per group, level or term: n[<variable>|<level>], pct[…], valid_pct[…], cum_pct[…], ci_low[…], ci_high[…], sim_low[…], sim_high[…], k[<variable>], n_valid[…], n_missing[…], mode[…], mode_pct[…], entropy[…], imbalance[…]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Clopper–Pearson and Jeffreys intervals invert the beta distribution (scipy cephes vs R nmath): ~1e-13.
Python

The exact script CodeSplash ran for example “Survey wilson” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Frequencies (categorical variables)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.categorical 1.0.0 · spec a79864cc287a6a99
# Dataset: s1_survey (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import describe as csd

# %% Data
variables = ["smoke", "exercise", "sex"]
df = pd.read_parquet("tests/parity/fixtures/s1_survey.parquet", columns=variables)
level_order = {
    "smoke": ["Never", "Occas", "Regul", "Heavy"],
    "exercise": ["None", "Some", "Freq"],
    "sex": ["Female", "Male"],
}
for v in variables:
    if not level_order[v]:  # no stored order: sorted values
        level_order[v] = sorted(str(x) for x in df[v].dropna().unique())
    df[v] = pd.Categorical(df[v], categories=level_order[v])  # values outside the stored levels count as missing
conf = 0.95
ci_method = "wilson"  # pinned: Wilson unless chosen (Brown, Cai & DasGupta 2001)
simultaneous = False  # Goodman (1965) intervals that hold for all levels at once
order = "stored"
warnings = []

# %% Frequencies
rows, values = [], {"n_rows": len(df)}
summaries = []
for v in variables:
    x = df[v]
    n_total = len(x)
    n_missing = int(x.isna().sum())
    n_valid = n_total - n_missing
    counts = np.array([int((x == lv).sum()) for lv in level_order[v]])
    idx = list(range(len(counts)))
    if order == "frequency":
        idx.sort(key=lambda i: (-counts[i], i))
    if simultaneous and n_valid > 0:
        sim_lo, sim_hi = csd.goodman_ci(counts, conf)
    cum = 0
    for i in idx:
        lv, c = level_order[v][i], int(counts[i])
        cum += c
        lo, hi = csd.prop_ci(c, n_valid, conf, ci_method) if n_valid else (float("nan"), float("nan"))
        row = {
            "variable": v, "level": lv, "n": c,
            "pct": c / n_total if n_total else float("nan"),
            "valid_pct": c / n_valid if n_valid else float("nan"),
            "cum_pct": cum / n_valid if n_valid else float("nan"),
            "ci_low": lo, "ci_high": hi,
        }
        if simultaneous:
            row["sim_low"] = float(sim_lo[i]) if n_valid else float("nan")
            row["sim_high"] = float(sim_hi[i]) if n_valid else float("nan")
        rows.append(row)
        for k in ("n", "pct", "valid_pct", "cum_pct", "ci_low", "ci_high") + (("sim_low", "sim_high") if simultaneous else ()):
            values[f"{k}[{v}|{lv}]"] = row[k]
    if n_missing:
        rows.append({"variable": v, "level": "(missing)", "n": n_missing, "pct": n_missing / n_total})
    mode_i = int(np.argmax(counts)) if counts.size and counts.max() > 0 else None
    summary = {
        "variable": v, "k": len(counts), "n_valid": n_valid, "n_missing": n_missing,
        "mode": "" if mode_i is None else level_order[v][mode_i],
        "mode_pct": float("nan") if mode_i is None or not n_valid else counts[mode_i] / n_valid,
        "entropy": csd.entropy_bits(counts),
    }
    k_obs = int((counts > 0).sum())
    summary["imbalance"] = 1 - summary["entropy"] / np.log2(k_obs) if k_obs > 1 else float("nan")
    summaries.append(summary)
    for k in ("k", "n_valid", "n_missing", "mode", "mode_pct", "entropy", "imbalance"):
        values[f"{k}[{v}]"] = summary[k]
    rare = [level_order[v][i] for i in range(len(counts)) if 0 < counts[i] < 0.01 * n_valid]
    if rare:
        warnings.append(f"{v}: {len(rare)} rare level{'s' if len(rare) > 1 else ''} (< 1% of valid values): {', '.join(rare[:8])}.")
    empty = [level_order[v][i] for i in range(len(counts)) if counts[i] == 0]
    if empty:
        warnings.append(f"{v}: no observations in {', '.join(empty[:8])}.")

# %% Result
lead = summaries[0]
values.update({"lead": lead["variable"], "n_variables": len(variables)})
pct = f"{conf:.0%}"
method_label = {"wilson": "Wilson", "clopper-pearson": "Clopper–Pearson (exact)", "jeffreys": "Jeffreys",
                "agresti-coull": "Agresti–Coull", "wald": "Wald"}[ci_method]
values["ci_method_label"] = method_label
columns = [
    {"key": "variable", "label": "Variable", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
    {"key": "n", "label": "n", "type": "integer"}, {"key": "pct", "label": "% of rows", "type": "percent"},
    {"key": "valid_pct", "label": "Valid %", "type": "percent"}, {"key": "cum_pct", "label": "Cumulative %", "type": "percent"},
    {"key": "ci_low", "label": f"{pct} CI low", "type": "percent"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "percent"},
]
if simultaneous:
    columns += [{"key": "sim_low", "label": "Simultaneous low", "type": "percent"}, {"key": "sim_high", "label": "Simultaneous high", "type": "percent"}]
v0 = variables[0]
chart_df = df[df[v0].notna()]
chart_rows = np.unique(np.round(np.linspace(0, len(chart_df) - 1, min(len(chart_df), 5000))).astype(int)) if len(chart_df) else np.array([], dtype=int)
cs.publish({
    "method": "describe.categorical",
    "methodVersion": "1.0.0",
    "title": "Frequencies",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(df),
    "summary": f"{lead['variable']}: {lead['k']} categories; most common {lead['mode']} ({lead['mode_pct']:.1%} of valid values), {lead['n_missing']} missing.",
    "statistics": [{"key": "n_rows", "label": "Rows", "value": len(df)}, {"key": "variables", "label": "Variables", "value": len(variables)}],
    "tables": [
        {"key": "frequencies", "title": "Frequencies", "columns": columns, "rows": rows,
         "note": f"Valid % and intervals exclude missing values; {method_label} {pct} intervals" + ("; Goodman simultaneous intervals hold for all levels together." if simultaneous else ".")},
        {"key": "summary", "title": "Summary by variable",
         "columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "k", "label": "Levels", "type": "integer"},
                     {"key": "n_valid", "label": "Valid", "type": "integer"}, {"key": "n_missing", "label": "Missing", "type": "integer"},
                     {"key": "mode", "label": "Most common", "type": "string"}, {"key": "mode_pct", "label": "Its share", "type": "percent"},
                     {"key": "entropy", "label": "Entropy (bits)", "type": "number"}, {"key": "imbalance", "label": "Imbalance", "type": "number"}],
         "rows": summaries},
    ],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": ["Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates."],
    "charts": [cs.chart("frequencies", "bar", f"{v0}", {"x": cs.col(v0, chart_df[v0].astype(str).to_numpy()[chart_rows], levels=level_order[v0])},
                        controls={"order": "freq" if order == "frequency" else "alpha"})],
    "values": values,
})
R

The exact script CodeSplash ran for example “Survey wilson” · R version 4.5.1 (2025-06-13)

# Frequencies (categorical variables)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.categorical 1.0.0 · spec a79864cc287a6a99
# Dataset: s1_survey (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
variables <- c("smoke", "exercise", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_survey.parquet", col_select = variables))
level_order <- list(
  "smoke" = c("Never", "Occas", "Regul", "Heavy"),
  "exercise" = c("None", "Some", "Freq"),
  "sex" = c("Female", "Male")
)
for (v in variables) {
  if (is.null(level_order[[v]])) level_order[[v]] <- sort(unique(as.character(df[[v]][!is.na(df[[v]])])), method = "radix")
  df[[v]] <- factor(df[[v]], levels = level_order[[v]])  # values outside the stored levels count as missing
}
conf <- 0.95
ci_method <- "wilson"  # pinned: Wilson unless chosen (Brown, Cai & DasGupta 2001)
simultaneous <- FALSE  # Goodman (1965) intervals that hold for all levels at once
ord <- "stored"
warnings <- list()

# %% Frequencies
rows <- list()
values <- list(n_rows = nrow(df))
summaries <- list()
for (v in variables) {
  x <- df[[v]]
  n_total <- length(x)
  n_missing <- sum(is.na(x))
  n_valid <- n_total - n_missing
  lv_all <- level_order[[v]]
  counts <- vapply(lv_all, function(lv) sum(x == lv, na.rm = TRUE), numeric(1))
  idx <- seq_along(counts)
  if (ord == "frequency") idx <- idx[order(-counts, idx)]
  if (simultaneous && n_valid > 0) sim <- cs_goodman_ci(counts, conf)
  cum <- 0
  for (i in idx) {
    lv <- lv_all[i]
    c <- counts[[i]]
    cum <- cum + c
    ci <- if (n_valid) cs_prop_ci(c, n_valid, conf, ci_method) else c(NaN, NaN)
    row <- list(variable = v, level = lv, n = c,
                pct = if (n_total) c / n_total else NaN,
                valid_pct = if (n_valid) c / n_valid else NaN,
                cum_pct = if (n_valid) cum / n_valid else NaN,
                ci_low = ci[1], ci_high = ci[2])
    if (simultaneous) {
      row$sim_low <- if (n_valid) sim$low[i] else NaN
      row$sim_high <- if (n_valid) sim$high[i] else NaN
    }
    rows[[length(rows) + 1]] <- row
    for (k in c("n", "pct", "valid_pct", "cum_pct", "ci_low", "ci_high", if (simultaneous) c("sim_low", "sim_high"))) {
      values[[sprintf("%s[%s|%s]", k, v, lv)]] <- row[[k]]
    }
  }
  if (n_missing) rows[[length(rows) + 1]] <- list(variable = v, level = "(missing)", n = n_missing, pct = n_missing / n_total)
  mode_i <- if (length(counts) && max(counts) > 0) which.max(counts) else NA
  ent <- cs_entropy_bits(counts)
  k_obs <- sum(counts > 0)
  summary <- list(variable = v, k = length(counts), n_valid = n_valid, n_missing = n_missing,
                  mode = if (is.na(mode_i)) "" else lv_all[mode_i],
                  mode_pct = if (is.na(mode_i) || !n_valid) NaN else counts[[mode_i]] / n_valid,
                  entropy = ent,
                  imbalance = if (k_obs > 1) 1 - ent / log2(k_obs) else NaN)
  summaries[[length(summaries) + 1]] <- summary
  for (k in c("k", "n_valid", "n_missing", "mode", "mode_pct", "entropy", "imbalance")) values[[sprintf("%s[%s]", k, v)]] <- summary[[k]]
  rare <- lv_all[counts > 0 & counts < 0.01 * n_valid]
  if (length(rare)) {
    warnings <- c(warnings, sprintf("%s: %d rare level%s (< 1%% of valid values): %s.", v, length(rare), if (length(rare) > 1) "s" else "",
                                    paste(utils::head(rare, 8), collapse = ", ")))
  }
  empty <- lv_all[counts == 0]
  if (length(empty)) warnings <- c(warnings, sprintf("%s: no observations in %s.", v, paste(utils::head(empty, 8), collapse = ", ")))
}

# %% Result
lead <- summaries[[1]]
values$lead <- lead$variable
values$n_variables <- length(variables)
pct <- sprintf("%.0f%%", conf * 100)
method_label <- c("wilson" = "Wilson", "clopper-pearson" = "Clopper–Pearson (exact)", "jeffreys" = "Jeffreys",
                  "agresti-coull" = "Agresti–Coull", "wald" = "Wald")[[ci_method]]
values$ci_method_label <- method_label
columns <- list(
  list(key = "variable", label = "Variable", type = "string"), list(key = "level", label = "Level", type = "string"),
  list(key = "n", label = "n", type = "integer"), list(key = "pct", label = "% of rows", type = "percent"),
  list(key = "valid_pct", label = "Valid %", type = "percent"), list(key = "cum_pct", label = "Cumulative %", type = "percent"),
  list(key = "ci_low", label = paste(pct, "CI low"), type = "percent"), list(key = "ci_high", label = paste(pct, "CI high"), type = "percent")
)
if (simultaneous) {
  columns <- c(columns, list(list(key = "sim_low", label = "Simultaneous low", type = "percent"), list(key = "sim_high", label = "Simultaneous high", type = "percent")))
}
v0 <- variables[1]
chart_x <- as.character(df[[v0]][!is.na(df[[v0]])])
chart_rows <- unique(round(seq(1, length(chart_x), length.out = min(length(chart_x), 5000))))
cs_publish(list(
  method = "describe.categorical",
  methodVersion = "1.0.0",
  title = "Frequencies",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = nrow(df),
  summary = sprintf("%s: %d categories; most common %s (%.1f%% of valid values), %d missing.", lead$variable, lead$k, lead$mode, 100 * lead$mode_pct, lead$n_missing),
  statistics = list(list(key = "n_rows", label = "Rows", value = nrow(df)), list(key = "variables", label = "Variables", value = length(variables))),
  tables = list(
    list(key = "frequencies", title = "Frequencies", columns = columns, rows = rows,
         note = paste0("Valid % and intervals exclude missing values; ", method_label, " ", pct, " intervals",
                       if (simultaneous) "; Goodman simultaneous intervals hold for all levels together." else ".")),
    list(key = "summary", title = "Summary by variable",
         columns = list(list(key = "variable", label = "Variable", type = "string"), list(key = "k", label = "Levels", type = "integer"),
                        list(key = "n_valid", label = "Valid", type = "integer"), list(key = "n_missing", label = "Missing", type = "integer"),
                        list(key = "mode", label = "Most common", type = "string"), list(key = "mode_pct", label = "Its share", type = "percent"),
                        list(key = "entropy", label = "Entropy (bits)", type = "number"), list(key = "imbalance", label = "Imbalance", type = "number")),
         rows = summaries)
  ),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = list("Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates."),
  charts = list(cs_chart("frequencies", "bar", v0, list(x = cs_col(v0, chart_x[chart_rows], levels = level_order[[v0]])),
                         controls = list(order = if (ord == "frequency") "freq" else "alpha"))),
  values = values
))

Sources

  • Brown, L. D., Cai, T. T., & DasGupta, A. (2001). Interval estimation for a binomial proportion. Statistical Science, 16, 101–133.
  • Goodman, L. A. (1965). On simultaneous confidence intervals for multinomial proportions. Technometrics, 7, 247–254.
  • Shannon, C. E. (1948). A mathematical theory of communication. Bell System Technical Journal, 27, 379–423.

From the CodeSplash method registry · describe.categorical v1.0.0.