Skip to content

Summarizing categories

Counts, percentages of all rows and of valid rows, cumulative percentages, and intervals that tell you how much a share can move.

Introductory ~8 min7 steps

What runs in CodeSplash

You will be able to

  • Tell percent of rows from valid percent
  • Give a share with a confidence interval
  • Read the imbalance of a categorical column
01

Counts first

Read

For a categorical column, the summary is a table: each level, its count and its share.

A classic survey of 592 students records hair color. Brown is the most common, with 286 students.

286592=48.3%\frac{286}{592} = 48.3\%

Always give the count with the percentage. "50% of respondents" means very different things for 4 people and for 4,000.

02

Which percent?

Predict

Predict first

100 people answered a survey, but 20 skipped the question on smoking. Of the 80 who answered, 16 smoke. What's the valid percent for smokers?

Make your guess between 0 and 100 %, then reveal.

Reveal

16/80=20%16 / 80 = 20\%. As a share of all rows it's 16/100=16%16 / 100 = 16\%. The valid percent assumes those who skipped resemble those who answered, so report the number missing as well.

03

How much could a share move?

In the app

A share from a sample has uncertainty. The Frequencies method gives an interval for each level, Wilson by default, and Clopper–Pearson, Jeffreys, Agresti–Coull or Wald if you ask.

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.
The exact R script · R 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
))
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.
The exact Python script · Python 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,
})

Wilson is a good default. Wald intervals misbehave near 0% and 100%, and with small samples.

04

See the coverage

Explore

Change the sample size and the true share and compare how often each interval contains the truth.

EExplorable · Do proportion intervals keep their promise?

How often does a 95% interval for a proportion really contain the truth?

How often does the textbook Wald interval cover the truth here?

0.50
How sure?
20
0.10

Confidence

statedp

Red: Wald. Blue: Wilson. The other: Clopper–Pearson, which never falls below the stated level and is often wider than needed. These are exact sums, not simulations.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

05

Charts for categories

Read

Sort bars by frequency unless the levels have a natural order, such as days or sizes. Few levels suit a plain bar chart, and many suit a ranked chart that groups the tail.

Ranked barsWhich categories lead on a total, mean or median?
View data
productrevenue
Routers174.90
Cables15.420
Chargers25.680
Cameras634.51
Speakers134.27
Phones427.04
Chargers14.110
Cables20.470
Headphones367.94
Routers166.60
Cables10.800
Cables13.520
Printers291.17
Laptops1422.50
Watches364.38
Speakers163.27
Chargers39.510
Keyboards93.420
Phones709.95
Cables9.830
Cables38
Phones892.99
Cables14.540
Laptops1326.02
Printers286.51
Keyboards100.27
Chargers34.410
Monitors309.54
Cables16.720
Laptops1431.28
Cables17.480
Tablets572.75
Laptops1638.78
Phones1347.67
Drives101.94
Chargers28.160
Cables17.350
Chargers31
Drives117.61
Cables13.800
Chargers37.350
Cables13.810
Laptops1844.74
Cables10.840
Chargers41.680
Cables29.340
Headphones182.94
Headphones259.47
Phones1109.36
Chargers32.690
Phones771
Headphones289.72
Keyboards203.65
Printers348.41
Tablets568.91
Tablets621.64
Monitors307.55
Headphones128.50
Keyboards53.630
Monitors244.66

First 60 of 1500 rows.

06

Check your understanding

Checkpoint

Check yourself

200 rows, 40 blanks, and 40 people chose "yes". What is the valid percent for "yes"?

Show the answer

Answer: 25

40 / (200 − 40) = 40 / 160.

Check yourself

Which sentence reports a share best?

Show the answer

Answer: a

Count, denominator and missing are all there, and the precision is sensible. The others hide the sample size or imply precision the data don't have.

Check yourself

3 of 40 patients had a side effect. Why might you prefer a Wilson interval to a Wald interval?

Show the answer

Answer: a

Wald uses the observed share to estimate its own uncertainty, which breaks down when the share is small.

07

Recap

Recap
  • Give counts with percentages, and say which denominator you used.
  • Valid percent assumes those who skipped resemble those who answered.
  • A share has an interval, and Wilson is a good default.

Concepts in this lesson