Outliers: investigate, don't delete
What to do once a value is flagged, from correcting an error to keeping it and showing how much it matters.
What runs in CodeSplash
- Outliers (univariate) Verified in Python and R
You will be able to
- Separate errors from real extreme values
- Flag outliers in a recipe without changing the data
- Report a result with and without an outlier
Read first
A flag is a question
ReadAn outlierOutlierA value far from the rest; it may be an error, a rare real case or a sign of a heavy-tailed process. rule tells you a value is far from the rest. It can't tell you why.
The highest ozone reading in airquality is 168 ppb, against a median of 31.5. Is that a broken sensor, or a very bad day in New York? Those call for opposite actions, and the number alone doesn't choose.
How much can a few values move?
PredictPredict first
A sample of 30 measurements has two values planted far from the rest. Which summary do they disturb more?
Reveal
The answer: The mean moves more
The mean, usually. In this sample the median is 10.2 and the mean is 10.1. The standard deviation suffers most, at 1.62, which is why z-score rules can hide the very values they look for.
Try the detectors
ExploreMove the planted outliers further out and see which rules flag them. Then raise the number of outliers and watch whether each rule still finds them.
AExplorable · Outlier detectors compared
Why do outliers hide from the z-score, and which rule finds them?
How many points will the z > 3 rule flag?
Commit your prediction above to see the result
Make your prediction to see the result.
Rules disagree because they answer different questions. The next track's outlier lesson compares them; here you need the response.
Four honest responses
Read| You find | Do this |
|---|---|
| A recording error, and you know the true value | Correct it, and record the correction |
| A recording error, and you don't know the true value | Mark it missing |
| A real value from a different population | Analyze that group separately, or narrow your question |
| A real value in your population | Keep it, and use a method that copes with it |
"It looks wrong" isn't on the list. Removing inconvenient values until the result looks right is how false findings get made.
Flag it in a recipe
In the appIn Prepare (⌘3), three steps handle outliers, from gentlest to strongest:
- Flag outliers adds a true/false column and a reason. Nothing else changes.
- Cap outliers (winsorize) pulls values back to learned or fixed bounds.
- Remove outlier rows drops the rows.
Start with the flag. In Analyze, the outliers method runs all the rules side by side:
Grubbs' G = 4.31, p < .001
- Flagged (any rule)
- 2
- Flagged by ≥ 2 rules
- 2
- Grubbs p
- < .001
- Dixon p
- < .001
Plots
View data
| Status | reading |
|---|---|
| Not flagged | 10.200 |
| Not flagged | 9.800 |
| Not flagged | 10.500 |
| Not flagged | 10.100 |
| Not flagged | 9.600 |
| Not flagged | 10.900 |
| Not flagged | 10.300 |
| Not flagged | 9.900 |
| Not flagged | 10 |
| Not flagged | 10.400 |
| Not flagged | 9.700 |
| Not flagged | 10.600 |
| Not flagged | 10.200 |
| Not flagged | 9.500 |
| Not flagged | 10.800 |
| Not flagged | 10.100 |
| Not flagged | 9.900 |
| Not flagged | 10.300 |
| Not flagged | 10 |
| Not flagged | 10.700 |
| Not flagged | 9.800 |
| Not flagged | 10.200 |
| Not flagged | 10.500 |
| Not flagged | 9.400 |
| Not flagged | 10.100 |
| Flagged | 14.900 |
| Not flagged | 10 |
| Not flagged | 10.300 |
| Flagged | 3.100 |
| Not flagged | 10.200 |
Rules
| Rule | Criterion | Flagged |
|---|---|---|
| Tukey fences (k = 1.5) | outside [9.188, 11.09] | 2 |
| z-score (|z| > 3) | SD with n − 1 | 1 |
| Modified z (|M| > 3.5) | median and MAD (Iglewicz & Hoaglin) | 2 |
| Grubbs' test | G = 4.307, p = 1.389e-06 | 1 |
| Generalized ESD (up to 3) | α = 0.05 | 2 |
| Dixon's Q test | r22: Q = 0.8312, p = 0.0001 (lowest value) | 1 |
| Tietjen–Moore (k = 2) | k = 2: E = 0.0502, p = 0.0001 | 2 |
Flagged values
| Row | id | reading | z | Modified z | Tukey | z rule | Mod. z | Grubbs | ESD | Dixon | T–M | Rules |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 29 | r29 | 3.100 | −4.307 | −19.021 | true | true | true | true | true | true | true | 4 |
| 26 | r26 | 14.900 | 2.988 | 12.815 | true | false | true | false | true | false | true | 3 |
Generalized ESD steps
| i | Value | R | λ (critical) | Outlier |
|---|---|---|---|---|
| 1 | 3.100 | 4.307 | 2.908 | true |
| 2 | 14.900 | 4.798 | 2.893 | true |
| 3 | 10.900 | 2.016 | 2.876 | false |
- Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. Never delete automatically; compare results with and without flagged values (sensitivity analysis).
- Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; Tietjen–Moore tests exactly k values chosen before looking at the data.
- Dixon and Tietjen–Moore p-values are Monte-Carlo (9,999 normal samples, seed 1); they match in Python and R.
The exact R script · R R version 4.5.1 (2025-06-13)
# Outliers (univariate)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method outliers.univariate 2.0.1 · spec 7fa75b43dd4df169
# Dataset: s1_outliers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_outliers.parquet", col_select = c("reading", "id")))
n_input <- nrow(df)
df[["id"]] <- factor(df[["id"]], levels = c("r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30")) # stored level order
df <- df[stats::complete.cases(df[c("reading", "id")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("reading", "id")) # infinite values stop the run (registry/errors.yaml)
# %% Rules
y <- "reading"
label <- "id"
if (!nzchar(label)) label <- NULL
group <- ""
if (!nzchar(group)) group <- NULL
x_all <- as.numeric(df[[y]])
rows_all <- as.integer(rownames(df)) # 1-based row numbers in the input
n <- length(x_all)
tukey_k <- 1.5
z_cut <- 3
modz_cut <- 3.5
alpha <- 0.05
gesd_k <- as.integer(3)
side <- "two_sided" # two_sided, upper or lower (prespecified)
dixon_type <- "auto"
tm_k <- as.integer(2)
reps <- as.integer(9999)
seed <- as.integer(1)
num_or_null <- function(v) if (is.null(v) || length(v) == 0 || !is.finite(v)) NULL else v
# Every rule on one sample; `idx` maps positions in x to rows of df.
screen <- function(x, rows_in, idx) {
n <- length(x)
fences <- cs_tukey_fences(x, tukey_k)
outer <- cs_tukey_fences(x, 3)
flag_tukey <- x < fences[1] | x > fences[2]
z <- cs_zscores(x)
z_enabled <- n > 10 # with n <= 10, |z| can never exceed (n - 1) / sqrt(n)
flag_z <- if (z_enabled) abs(z) > z_cut else rep(FALSE, n)
mz <- cs_modified_z(x)
flag_modz <- abs(mz) > modz_cut
gr <- cs_grubbs(x, side)
flag_grubbs <- rep(FALSE, n)
grubbs_row <- NULL
if (is.finite(gr$p) && gr$p < alpha) {
pos <- if (gr$side == "lowest") which.min(x) else which.max(x)
flag_grubbs[pos] <- TRUE
grubbs_row <- rows_in[pos]
}
ge <- cs_gesd(x, gesd_k, alpha)
flag_gesd <- rep(FALSE, n)
if (nrow(ge$steps)) flag_gesd[ge$steps$row[ge$steps$outlier]] <- TRUE
dx <- cs_dixon(x, dixon_type, side, reps, seed)
flag_dixon <- rep(FALSE, n)
if (is.finite(dx$p) && dx$p < alpha) flag_dixon[if (dx$side == "lowest") which.min(x) else which.max(x)] <- TRUE
tm <- cs_tietjen_moore(x, tm_k, side, reps, seed)
flag_tm <- rep(FALSE, n)
if (is.finite(tm$p) && tm$p < alpha) flag_tm[tm$rows] <- TRUE
count <- flag_tukey + flag_z + flag_modz + flag_gesd
any_flag <- count > 0 | flag_grubbs | flag_dixon | flag_tm
list(n = n, x = x, rows_in = rows_in, idx = idx, fences = fences, outer = outer, z = z, z_enabled = z_enabled, mz = mz,
gr = gr, grubbs_row = grubbs_row, ge = ge, dx = dx, tm = tm, count = count, any = any_flag,
flags = list(tukey = flag_tukey, z_rule = flag_z, modz_rule = flag_modz, grubbs = flag_grubbs, gesd = flag_gesd,
dixon = flag_dixon, tm = flag_tm))
}
if (is.null(group) && n < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "Outlier screening", min = 3, n = n)
if (n >= 1 && diff(range(x_all)) == 0) cs_error("CS_E_CONSTANT", column = y) # no variation: SD and MAD are 0
if (!is.null(group)) {
levels_g <- levels(df[[group]])
g_all <- as.character(df[[group]])
samples <- list()
for (lv in levels_g) {
m <- g_all == lv
if (sum(m) < 3) {
warnings <- c(warnings, sprintf("%s = %s has fewer than 3 values and was not screened.", group, lv))
next
}
samples[[length(samples) + 1]] <- list(level = lv, s = screen(x_all[m], rows_all[m], which(m)))
}
if (!length(samples)) cs_error("CS_E_UNDEFINED", what = "Outlier screening", reason = sprintf("no group of %s has at least 3 values", group))
} else {
samples <- list(list(level = NULL, s = screen(x_all, rows_all, seq_len(n))))
}
# %% Result
flagged <- list()
for (smp in samples) {
s <- smp$s
for (i in which(s$any)) {
flagged[[length(flagged) + 1]] <- c(
list(row = s$rows_in[i]), if (!is.null(group)) list(group = smp$level),
if (!is.null(label)) list(label = as.character(df[[label]][s$idx[i]])),
list(value = s$x[i], z = num_or_null(s$z[i]), modz = s$mz[i]),
lapply(s$flags, function(f) f[i]), list(rules = s$count[i]))
}
}
if (length(flagged)) {
o <- order(-vapply(flagged, function(r) r$rules, numeric(1)), vapply(flagged, function(r) r$row, numeric(1)))
flagged <- flagged[o]
}
any_rows <- sort(unlist(lapply(samples, function(smp) smp$s$rows_in[smp$s$any])))
n_any <- sum(vapply(samples, function(smp) sum(smp$s$any), numeric(1)))
n_cons <- sum(vapply(samples, function(smp) sum(smp$s$count >= 2), numeric(1)))
values <- list(n = n, mean = mean(x_all), sd = stats::sd(x_all), median = stats::median(x_all),
n_flagged_any = n_any, n_consensus = n_cons, flagged_rows = I(as.integer(any_rows)),
n_groups = if (is.null(group)) 0L else length(samples), mc_reps = reps, tm_k = tm_k)
single_keys <- c("tukey_low", "tukey_high", "outer_low", "outer_high", "n_tukey", "n_tukey_outer", "n_z", "z_enabled", "max_abs_z",
"n_modz", "max_abs_modz", "grubbs_g", "grubbs_p", "grubbs_value", "grubbs_side", "grubbs_row", "gesd_n",
"dixon_type", "dixon_q", "dixon_p", "dixon_value", "dixon_side", "tm_e", "tm_p", "tm_side")
tables <- list()
if (is.null(group)) {
s <- samples[[1]]$s
x <- s$x; gr <- s$gr; ge <- s$ge; dx <- s$dx; tm <- s$tm; f <- s$flags
values$tukey_low <- s$fences[1]
values$tukey_high <- s$fences[2]
values$outer_low <- s$outer[1]
values$outer_high <- s$outer[2]
values$n_tukey <- sum(f$tukey)
values$n_tukey_outer <- sum(x < s$outer[1] | x > s$outer[2])
values$n_z <- sum(f$z_rule)
values$z_enabled <- s$z_enabled
values["max_abs_z"] <- list(if (s$z_enabled) max(abs(s$z), na.rm = TRUE) else NULL)
values$n_modz <- sum(f$modz_rule)
values$max_abs_modz <- max(abs(s$mz))
values$grubbs_g <- gr$g
values$grubbs_p <- gr$p
values$grubbs_value <- gr$value
values$grubbs_side <- gr$side
values["grubbs_row"] <- list(s$grubbs_row)
values$gesd_n <- ge$n_outliers
values["dixon_type"] <- list(if (is.finite(dx$q)) dx$type else NULL)
values["dixon_q"] <- list(num_or_null(dx$q))
values["dixon_p"] <- list(num_or_null(dx$p))
values["dixon_value"] <- list(num_or_null(dx$value))
values["dixon_side"] <- list(if (nzchar(dx$side)) dx$side else NULL)
values["tm_e"] <- list(num_or_null(tm$e))
values["tm_p"] <- list(num_or_null(tm$p))
values["tm_side"] <- list(if (nzchar(tm$side)) tm$side else NULL)
for (j in seq_len(nrow(ge$steps))) {
values[[sprintf("gesd_r[%d]", ge$steps$i[j])]] <- ge$steps$r[j]
values[[sprintf("gesd_lambda[%d]", ge$steps$i[j])]] <- ge$steps$lambda[j]
values[[sprintf("gesd_value[%d]", ge$steps$i[j])]] <- ge$steps$value[j]
}
dixon_crit <- if (is.finite(dx$q)) sprintf("%s: Q = %.4g, p = %.4g (%s value)", dx$type, dx$q, dx$p, dx$side) else "not used: Dixon's ratios cover 3–30 values"
tm_crit <- if (is.finite(tm$e)) sprintf("k = %d: E = %.4g, p = %.4g", tm_k, tm$e, tm$p) else sprintf("not used: needs more than %d values", tm_k + 1)
methods <- list(
list(method = sprintf("Tukey fences (k = %s)", format(tukey_k)), criterion = sprintf("outside [%.4g, %.4g]", s$fences[1], s$fences[2]), flagged = sum(f$tukey)),
list(method = sprintf("z-score (|z| > %s)", format(z_cut)), criterion = if (s$z_enabled) "SD with n − 1" else "not used: n ≤ 10", flagged = sum(f$z_rule)),
list(method = sprintf("Modified z (|M| > %s)", format(modz_cut)), criterion = "median and MAD (Iglewicz & Hoaglin)", flagged = sum(f$modz_rule)),
list(method = "Grubbs' test", criterion = sprintf("G = %.3f, p = %.4g", gr$g, gr$p), flagged = sum(f$grubbs)),
list(method = sprintf("Generalized ESD (up to %d)", gesd_k), criterion = sprintf("α = %s", format(alpha)), flagged = sum(f$gesd)),
list(method = "Dixon's Q test", criterion = dixon_crit, flagged = sum(f$dixon)),
list(method = sprintf("Tietjen–Moore (k = %d)", tm_k), criterion = tm_crit, flagged = sum(f$tm))
)
tables[[length(tables) + 1]] <- list(key = "rules", title = "Rules", columns = list(
list(key = "method", label = "Rule", type = "string"), list(key = "criterion", label = "Criterion", type = "string"),
list(key = "flagged", label = "Flagged", type = "integer")), rows = methods)
} else {
for (k in single_keys) values[k] <- list(NULL)
grows <- list()
for (smp in samples) {
lv <- smp$level
s <- smp$s
values[[sprintf("n[%s]", lv)]] <- s$n
values[[sprintf("n_flagged[%s]", lv)]] <- sum(s$any)
values[[sprintf("tukey_low[%s]", lv)]] <- s$fences[1]
values[[sprintf("tukey_high[%s]", lv)]] <- s$fences[2]
values[sprintf("grubbs_p[%s]", lv)] <- list(num_or_null(s$gr$p))
values[sprintf("dixon_p[%s]", lv)] <- list(num_or_null(s$dx$p))
values[sprintf("tm_p[%s]", lv)] <- list(num_or_null(s$tm$p))
grows[[length(grows) + 1]] <- list(group = lv, n = s$n, flagged = sum(s$any), tukey_low = s$fences[1], tukey_high = s$fences[2],
grubbs_p = num_or_null(s$gr$p), gesd_n = s$ge$n_outliers, dixon_p = num_or_null(s$dx$p),
tm_p = num_or_null(s$tm$p))
}
tables[[length(tables) + 1]] <- list(key = "groups", title = sprintf("Rules within each %s", group), columns = list(
list(key = "group", label = group, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "flagged", label = "Flagged", type = "integer"), list(key = "tukey_low", label = "Lower fence", type = "number"),
list(key = "tukey_high", label = "Upper fence", type = "number"), list(key = "grubbs_p", label = "Grubbs p", type = "p"),
list(key = "gesd_n", label = "ESD outliers", type = "integer"), list(key = "dixon_p", label = "Dixon p", type = "p"),
list(key = "tm_p", label = "Tietjen–Moore p", type = "p")), rows = grows)
}
flag_cols <- c(list(list(key = "row", label = "Row", type = "integer")),
if (!is.null(group)) list(list(key = "group", label = group, type = "string")),
if (!is.null(label)) list(list(key = "label", label = label, type = "string")),
list(list(key = "value", label = y, type = "number"), list(key = "z", label = "z", type = "number"),
list(key = "modz", label = "Modified z", type = "number"), list(key = "tukey", label = "Tukey", type = "string"),
list(key = "z_rule", label = "z rule", type = "string"), list(key = "modz_rule", label = "Mod. z", type = "string"),
list(key = "grubbs", label = "Grubbs", type = "string"), list(key = "gesd", label = "ESD", type = "string"),
list(key = "dixon", label = "Dixon", type = "string"), list(key = "tm", label = "T–M", type = "string"),
list(key = "rules", label = "Rules", type = "integer")))
tables[[length(tables) + 1]] <- list(key = "flagged", title = "Flagged values", columns = flag_cols, rows = flagged)
if (is.null(group)) {
s <- samples[[1]]$s
gesd_rows <- if (nrow(s$ge$steps)) {
steps <- s$ge$steps
steps$row <- s$rows_in[steps$row]
steps
} else list()
tables[[length(tables) + 1]] <- list(key = "gesd", title = "Generalized ESD steps",
columns = list(list(key = "i", label = "i", type = "integer"), list(key = "value", label = "Value", type = "number"),
list(key = "r", label = "R", type = "number"), list(key = "lambda", label = "λ (critical)", type = "number"),
list(key = "outlier", label = "Outlier", type = "string")),
rows = gesd_rows)
}
any_mask <- rep(FALSE, n)
for (smp in samples) any_mask[smp$s$idx[smp$s$any]] <- TRUE
chart_rows <- unique(round(seq(1, n, length.out = min(n, 5000))))
status <- ifelse(any_mask, "Flagged", "Not flagged")
small_n <- is.null(group) && !samples[[1]]$s$z_enabled
gr0 <- samples[[1]]$s$gr
cs_publish(list(
method = "outliers.univariate",
methodVersion = "2.0.1",
title = "Outliers",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = paste0(sprintf("%s: %d of %d values flagged by at least one rule, %d by two or more", y, n_any, n, n_cons),
if (!is.null(group)) sprintf(" (each %s screened on its own).", group) else "."),
apa = if (!is.null(group)) "" else sprintf("Grubbs' G = %s, %s", cs_fmt_num(gr0$g), cs_fmt_p(gr0$p)),
statistics = c(list(list(key = "n_flagged_any", label = "Flagged (any rule)", value = n_any),
list(key = "n_consensus", label = "Flagged by ≥ 2 rules", value = n_cons)),
if (is.null(group)) list(list(key = "grubbs_p", label = "Grubbs p", value = gr0$p, format = "p"),
list(key = "dixon_p", label = "Dixon p", value = values$dixon_p, format = "p"))),
tables = tables,
effectSizes = list(),
assumptions = list(),
warnings = c(warnings, if (small_n) list("With 10 or fewer values the z rule cannot flag anything; it is not used.")),
notes = list(paste("Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values.",
"Never delete automatically; compare results with and without flagged values (sensitivity analysis)."),
paste("Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values;",
"Tietjen–Moore tests exactly k values chosen before looking at the data."),
sprintf("Dixon and Tietjen–Moore p-values are Monte-Carlo (%s normal samples, seed %d); they match in Python and R.",
format(reps, big.mark = ","), seed)),
charts = list(cs_chart("values", "strip", sprintf("%s: flagged vs not flagged", y), list(
y = cs_col(y, x_all[chart_rows]), group = cs_col("Status", status[chart_rows], levels = c("Not flagged", "Flagged"))),
controls = list(interval = "none"))),
values = values
))
Grubbs' G = 4.31, p < .001
- Flagged (any rule)
- 2
- Flagged by ≥ 2 rules
- 2
- Grubbs p
- < .001
- Dixon p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Rules
| Rule | Criterion | Flagged |
|---|---|---|
| Tukey fences (k = 1.5) | outside [9.188, 11.09] | 2 |
| z-score (|z| > 3) | SD with n − 1 | 1 |
| Modified z (|M| > 3.5) | median and MAD (Iglewicz & Hoaglin) | 2 |
| Grubbs' test | G = 4.307, p = 1.389e-06 | 1 |
| Generalized ESD (up to 3) | α = 0.05 | 2 |
| Dixon's Q test | r22: Q = 0.8312, p = 0.0001 (lowest value) | 1 |
| Tietjen–Moore (k = 2) | k = 2: E = 0.0502, p = 0.0001 | 2 |
Flagged values
| Row | id | reading | z | Modified z | Tukey | z rule | Mod. z | Grubbs | ESD | Dixon | T–M | Rules |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 29 | r29 | 3.100 | −4.307 | −19.021 | true | true | true | true | true | true | true | 4 |
| 26 | r26 | 14.900 | 2.988 | 12.815 | true | false | true | false | true | false | true | 3 |
Generalized ESD steps
| i | Value | R | λ (critical) | Outlier |
|---|---|---|---|---|
| 1 | 3.100 | 4.307 | 2.908 | true |
| 2 | 14.900 | 4.798 | 2.893 | true |
| 3 | 10.900 | 2.016 | 2.876 | false |
- Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. Never delete automatically; compare results with and without flagged values (sensitivity analysis).
- Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; Tietjen–Moore tests exactly k values chosen before looking at the data.
- Dixon and Tietjen–Moore p-values are Monte-Carlo (9,999 normal samples, seed 1); they match in Python and R.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Outliers (univariate)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method outliers.univariate 2.0.1 · spec 7fa75b43dd4df169
# Dataset: s1_outliers (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 outliers as cso
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_outliers.parquet", columns=["reading", "id"])
n_input = len(df)
df["id"] = pd.Categorical(df["id"], categories=["r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30"]) # stored level order
df = df.dropna(subset=["reading", "id"]) # listwise deletion over the analysis columns
df["id"] = df["id"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["reading", "id"]) # infinite values stop the run (registry/errors.yaml)
# %% Rules
y = "reading"
label = "id" or None
group = "" or None
x_all = df[y].to_numpy(dtype=float)
rows_all = (df.index.to_numpy() + 1).astype(int) # 1-based row numbers in the input
n = x_all.size
tukey_k = 1.5
z_cut = 3
modz_cut = 3.5
alpha = 0.05
gesd_k = int(3)
side = "two_sided" # two_sided, upper or lower (prespecified)
dixon_type = "auto"
tm_k = int(2)
reps = int(9999)
seed = int(1)
def screen(x, rows_in, idx):
"""Every rule on one sample; positions in the result index ``x`` (``idx`` maps them to ``df`` rows)."""
n = x.size
lo, hi = cso.tukey_fences(x, tukey_k)
olo, ohi = cso.tukey_fences(x, 3.0)
flag_tukey = (x < lo) | (x > hi)
z = cso.zscores(x)
z_enabled = n > 10 # with n ≤ 10, |z| can never exceed (n − 1)/√n
flag_z = (np.abs(z) > z_cut) if z_enabled else np.zeros(n, bool)
mz = cso.modified_z(x)
flag_modz = np.abs(mz) > modz_cut
gr = cso.grubbs(x, side)
flag_grubbs = np.zeros(n, bool)
grubbs_row = None
if np.isfinite(gr["p"]) and gr["p"] < alpha:
pos = int(np.argmin(x)) if gr["side"] == "lowest" else int(np.argmax(x))
flag_grubbs[pos] = True
grubbs_row = int(rows_in[pos])
ge = cso.gesd(x, gesd_k, alpha)
flag_gesd = np.zeros(n, bool)
for st in ge["steps"]:
if st["outlier"]:
flag_gesd[st["row"]] = True
dx = cso.dixon(x, dixon_type, side, reps, seed)
flag_dixon = np.zeros(n, bool)
if np.isfinite(dx["p"]) and dx["p"] < alpha:
flag_dixon[int(np.argmin(x)) if dx["side"] == "lowest" else int(np.argmax(x))] = True
tm = cso.tietjen_moore(x, tm_k, side, reps, seed)
flag_tm = np.zeros(n, bool)
if np.isfinite(tm["p"]) and tm["p"] < alpha:
flag_tm[tm["rows"]] = True
count = flag_tukey.astype(int) + flag_z.astype(int) + flag_modz.astype(int) + flag_gesd.astype(int)
any_flag = (count > 0) | flag_grubbs | flag_dixon | flag_tm
return {"n": n, "x": x, "rows_in": rows_in, "idx": idx, "lo": lo, "hi": hi, "olo": olo, "ohi": ohi, "z": z, "z_enabled": z_enabled,
"mz": mz, "gr": gr, "grubbs_row": grubbs_row, "ge": ge, "dx": dx, "tm": tm, "count": count, "any": any_flag,
"flags": {"tukey": flag_tukey, "z_rule": flag_z, "modz_rule": flag_modz, "grubbs": flag_grubbs, "gesd": flag_gesd,
"dixon": flag_dixon, "tm": flag_tm}}
def num(v):
return None if v is None or not np.isfinite(v) else float(v)
if not group and n < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Outlier screening", min=3, n=n)
if n >= 1 and np.ptp(x_all) == 0: # no variation: SD and MAD are 0, so no rule can flag anything
cs.cs_error("CS_E_CONSTANT", column=y)
if group:
levels = [str(lv) for lv in df[group].cat.categories]
g_all = df[group].astype(str).to_numpy()
samples = []
for lv in levels:
m = g_all == lv
if m.sum() < 3:
warnings.append(f"{group} = {lv} has fewer than 3 values and was not screened.")
continue
samples.append((lv, screen(x_all[m], rows_all[m], np.flatnonzero(m))))
if not samples:
cs.cs_error("CS_E_UNDEFINED", what="Outlier screening", reason=f"no group of {group} has at least 3 values")
else:
samples = [(None, screen(x_all, rows_all, np.arange(n)))]
# %% Result
flagged = []
for lv, s in samples:
for i in np.flatnonzero(s["any"]):
flagged.append({
"row": int(s["rows_in"][i]), **({"group": lv} if group else {}),
**({"label": str(df[label].iloc[int(s["idx"][i])])} if label else {}),
"value": float(s["x"][i]), "z": num(s["z"][i]), "modz": float(s["mz"][i]),
**{k: bool(f[i]) for k, f in s["flags"].items()}, "rules": int(s["count"][i]),
})
flagged.sort(key=lambda r: (-r["rules"], r["row"]))
any_rows = sorted(int(r) for _, s in samples for r in s["rows_in"][s["any"]])
n_any = sum(int(s["any"].sum()) for _, s in samples)
n_cons = sum(int((s["count"] >= 2).sum()) for _, s in samples)
values = {"n": n, "mean": float(x_all.mean()), "sd": float(x_all.std(ddof=1)), "median": float(np.median(x_all)),
"n_flagged_any": n_any, "n_consensus": n_cons, "flagged_rows": any_rows, "n_groups": len(samples) if group else 0,
"mc_reps": reps, "tm_k": tm_k}
single_keys = ["tukey_low", "tukey_high", "outer_low", "outer_high", "n_tukey", "n_tukey_outer", "n_z", "z_enabled", "max_abs_z",
"n_modz", "max_abs_modz", "grubbs_g", "grubbs_p", "grubbs_value", "grubbs_side", "grubbs_row", "gesd_n",
"dixon_type", "dixon_q", "dixon_p", "dixon_value", "dixon_side", "tm_e", "tm_p", "tm_side"]
tables = []
if not group:
s = samples[0][1]
x, gr, ge, dx, tm, f = s["x"], s["gr"], s["ge"], s["dx"], s["tm"], s["flags"]
values.update({
"tukey_low": s["lo"], "tukey_high": s["hi"], "outer_low": s["olo"], "outer_high": s["ohi"],
"n_tukey": int(f["tukey"].sum()), "n_tukey_outer": int(((x < s["olo"]) | (x > s["ohi"])).sum()),
"n_z": int(f["z_rule"].sum()), "z_enabled": bool(s["z_enabled"]),
"max_abs_z": float(np.nanmax(np.abs(s["z"]))) if s["z_enabled"] else None,
"n_modz": int(f["modz_rule"].sum()), "max_abs_modz": float(np.max(np.abs(s["mz"]))),
"grubbs_g": gr["g"], "grubbs_p": gr["p"], "grubbs_value": gr["value"], "grubbs_side": gr["side"], "grubbs_row": s["grubbs_row"],
"gesd_n": int(ge["n_outliers"]),
"dixon_type": dx["type"] if np.isfinite(dx["q"]) else None, "dixon_q": num(dx["q"]), "dixon_p": num(dx["p"]), "dixon_value": num(dx["value"]),
"dixon_side": dx["side"] or None, "tm_e": num(tm["e"]), "tm_p": num(tm["p"]), "tm_side": tm["side"] or None,
})
for st in ge["steps"]:
values[f"gesd_r[{st['i']}]"] = st["r"]
values[f"gesd_lambda[{st['i']}]"] = st["lambda"]
values[f"gesd_value[{st['i']}]"] = st["value"]
dixon_crit = (f"{dx['type']}: Q = {dx['q']:.4g}, p = {dx['p']:.4g} ({dx['side']} value)" if np.isfinite(dx["q"])
else "not used: Dixon's ratios cover 3–30 values")
tm_crit = (f"k = {tm_k}: E = {tm['e']:.4g}, p = {tm['p']:.4g}" if np.isfinite(tm["e"]) else f"not used: needs more than {tm_k + 1} values")
methods = [
{"method": f"Tukey fences (k = {tukey_k:g})", "criterion": f"outside [{s['lo']:.4g}, {s['hi']:.4g}]", "flagged": int(f["tukey"].sum())},
{"method": f"z-score (|z| > {z_cut:g})", "criterion": "SD with n − 1" if s["z_enabled"] else "not used: n ≤ 10", "flagged": int(f["z_rule"].sum())},
{"method": f"Modified z (|M| > {modz_cut:g})", "criterion": "median and MAD (Iglewicz & Hoaglin)", "flagged": int(f["modz_rule"].sum())},
{"method": "Grubbs' test", "criterion": f"G = {gr['g']:.3f}, p = {gr['p']:.4g}", "flagged": int(f["grubbs"].sum())},
{"method": f"Generalized ESD (up to {gesd_k})", "criterion": f"α = {alpha:g}", "flagged": int(f["gesd"].sum())},
{"method": "Dixon's Q test", "criterion": dixon_crit, "flagged": int(f["dixon"].sum())},
{"method": f"Tietjen–Moore (k = {tm_k})", "criterion": tm_crit, "flagged": int(f["tm"].sum())},
]
tables.append({"key": "rules", "title": "Rules", "columns": [{"key": "method", "label": "Rule", "type": "string"},
{"key": "criterion", "label": "Criterion", "type": "string"}, {"key": "flagged", "label": "Flagged", "type": "integer"}],
"rows": methods})
else:
for k in single_keys:
values[k] = None
grows = []
for lv, s in samples:
values[f"n[{lv}]"] = int(s["n"])
values[f"n_flagged[{lv}]"] = int(s["any"].sum())
values[f"tukey_low[{lv}]"] = s["lo"]
values[f"tukey_high[{lv}]"] = s["hi"]
values[f"grubbs_p[{lv}]"] = num(s["gr"]["p"])
values[f"dixon_p[{lv}]"] = num(s["dx"]["p"])
values[f"tm_p[{lv}]"] = num(s["tm"]["p"])
grows.append({"group": lv, "n": int(s["n"]), "flagged": int(s["any"].sum()), "tukey_low": s["lo"], "tukey_high": s["hi"],
"grubbs_p": num(s["gr"]["p"]), "gesd_n": int(s["ge"]["n_outliers"]), "dixon_p": num(s["dx"]["p"]), "tm_p": num(s["tm"]["p"])})
tables.append({"key": "groups", "title": f"Rules within each {group}", "columns": [
{"key": "group", "label": group, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "flagged", "label": "Flagged", "type": "integer"}, {"key": "tukey_low", "label": "Lower fence", "type": "number"},
{"key": "tukey_high", "label": "Upper fence", "type": "number"}, {"key": "grubbs_p", "label": "Grubbs p", "type": "p"},
{"key": "gesd_n", "label": "ESD outliers", "type": "integer"}, {"key": "dixon_p", "label": "Dixon p", "type": "p"},
{"key": "tm_p", "label": "Tietjen–Moore p", "type": "p"}], "rows": grows})
flag_cols = ([{"key": "row", "label": "Row", "type": "integer"}] + ([{"key": "group", "label": group, "type": "string"}] if group else [])
+ ([{"key": "label", "label": label, "type": "string"}] if label else []) + [
{"key": "value", "label": y, "type": "number"}, {"key": "z", "label": "z", "type": "number"}, {"key": "modz", "label": "Modified z", "type": "number"},
{"key": "tukey", "label": "Tukey", "type": "string"}, {"key": "z_rule", "label": "z rule", "type": "string"},
{"key": "modz_rule", "label": "Mod. z", "type": "string"}, {"key": "grubbs", "label": "Grubbs", "type": "string"},
{"key": "gesd", "label": "ESD", "type": "string"}, {"key": "dixon", "label": "Dixon", "type": "string"},
{"key": "tm", "label": "T–M", "type": "string"}, {"key": "rules", "label": "Rules", "type": "integer"},
])
tables.append({"key": "flagged", "title": "Flagged values", "columns": flag_cols, "rows": flagged})
if not group:
s = samples[0][1]
tables.append({"key": "gesd", "title": "Generalized ESD steps",
"columns": [{"key": "i", "label": "i", "type": "integer"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "r", "label": "R", "type": "number"}, {"key": "lambda", "label": "λ (critical)", "type": "number"},
{"key": "outlier", "label": "Outlier", "type": "string"}],
"rows": [{**st, "row": int(s["rows_in"][st["row"]])} for st in s["ge"]["steps"]]})
any_mask = np.zeros(n, bool)
for _, s in samples:
any_mask[s["idx"][s["any"]]] = True
chart_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
status = np.where(any_mask, "Flagged", "Not flagged")
small_n = (not group) and not samples[0][1]["z_enabled"]
gr0 = samples[0][1]["gr"]
cs.publish({
"method": "outliers.univariate",
"methodVersion": "2.0.1",
"title": "Outliers",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": f"{y}: {n_any} of {n} values flagged by at least one rule, {n_cons} by two or more"
+ (f" (each {group} screened on its own)." if group else "."),
"apa": "" if group else f"Grubbs' G = {cs.fmt_num(gr0['g'])}, {cs.fmt_p(gr0['p'])}",
"statistics": [{"key": "n_flagged_any", "label": "Flagged (any rule)", "value": n_any},
{"key": "n_consensus", "label": "Flagged by ≥ 2 rules", "value": n_cons}]
+ ([] if group else [{"key": "grubbs_p", "label": "Grubbs p", "value": gr0["p"], "format": "p"},
{"key": "dixon_p", "label": "Dixon p", "value": values["dixon_p"], "format": "p"}]),
"tables": tables,
"effectSizes": [],
"assumptions": [],
"warnings": warnings + (["With 10 or fewer values the z rule cannot flag anything; it is not used."] if small_n else []),
"notes": ["Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. "
"Never delete automatically; compare results with and without flagged values (sensitivity analysis).",
"Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; "
"Tietjen–Moore tests exactly k values chosen before looking at the data.",
f"Dixon and Tietjen–Moore p-values are Monte-Carlo ({reps:,} normal samples, seed {seed}); they match in Python and R."],
"charts": [cs.chart("values", "strip", f"{y}: flagged vs not flagged", {
"y": cs.col(y, x_all[chart_rows]), "group": cs.col("Status", status[chart_rows], levels=["Not flagged", "Flagged"])},
controls={"interval": "none"})],
"values": values,
})
Show both results
ReflectWhen you can't settle whether a value belongs, run the analysis with and without it, then report both. If the conclusion survives, the value doesn't matter and you can say so. If it flips, your readers need to know that too.
Which of your recent analyses would change if its most extreme row were gone?
Check your understanding
CheckpointCheck yourself
One patient's cholesterol is far above everyone else's. The lab confirms the reading is correct. What should you do?
Show the answer
Answer: b
A confirmed value belongs to your data. Deleting or replacing it answers a different question from the one you set out to ask.
Check yourself
You don't yet know whether flagged readings are errors. Which Prepare step keeps your options open?
Show the answer
Answer: a
A flag changes no values, and you can filter or model on it later. The other two make the decision for you.
Recap
Recap- A flag is a question about why, and the answer decides the action.
- Correct real errors, keep real values, and never remove a point because it spoils the result.
- When unsure, report the analysis both ways.
Concepts in this lesson