Skip to content

ADescribe · transform.power

Power transformation (Box–Cox / Yeo–Johnson)

Which power transformation makes a skewed variable closest to normal?

The maximum-likelihood Box–Cox (positive values) or Yeo–Johnson (any values) λ with a profile-likelihood interval, likelihood-ratio tests of λ = 1 (no transformation) and λ = 0 (log), an interpretable suggested λ, and skewness and Shapiro–Wilk before and after.

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

A real result

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

Box–Cox transformationRecorded · Python and R agreeRecorded 2026-11-17 · 18 values compared
R

λ = 0.20, 95% CI [0.03, 0.39]

λ (maximum likelihood)
0.2034
95% CI (profile likelihood)
[0.0299, 0.3915]
Suggested λ
0.2000

Plots

Ozone (original)How is one numeric variable distributed?
View data
Ozone
41
36
12
18
28
23
19
8
7
16
11
14
18
14
34
6
30
11
1
11
4
32
23
45
115
37
29
71
39
23
21
37
20
12
13
135
49
32
64
40
77
97
97
85
10
27
7
48
35
61
79
63
16
80
108
20
52
82
50
64

First 60 of 116 rows.

Ozone transformed (λ = 0.20)How is one numeric variable distributed?
View data
Ozone (λ = 0.20)
5.547
5.274
3.233
3.934
4.766
4.387
4.032
2.588
2.387
3.725
3.091
3.493
3.934
3.493
5.156
2.162
4.903
3.091
0
3.091
1.601
5.033
4.387
5.747
7.989
5.331
4.836
6.784
5.441
4.387
4.216
5.331
4.126
3.233
3.367
8.417
5.934
5.033
6.539
5.495
6.978
7.550
7.550
7.220
2.937
4.695
2.387
5.888
5.216
6.428
7.041
6.503
3.725
7.071
7.826
4.126
6.066
7.132
5.978
6.539

First 60 of 116 rows.

Normal Q–Q after transformationIs a variable (or a set of residuals) approximately normal, and where does it depart?
View data
Ozone (λ = 0.20)
5.547
5.274
3.233
3.934
4.766
4.387
4.032
2.588
2.387
3.725
3.091
3.493
3.934
3.493
5.156
2.162
4.903
3.091
0
3.091
1.601
5.033
4.387
5.747
7.989
5.331
4.836
6.784
5.441
4.387
4.216
5.331
4.126
3.233
3.367
8.417
5.934
5.033
6.539
5.495
6.978
7.550
7.550
7.220
2.937
4.695
2.387
5.888
5.216
6.428
7.041
6.503
3.725
7.071
7.826
4.126
6.066
7.132
5.978
6.539

First 60 of 116 rows.

Profile log-likelihood of λ (Box–Cox)Which power transformation would make this outcome behave best?
View data
λProfile log-likelihood
−2−832.99
−1.967−821.73
−1.933−810.50
−1.900−799.32
−1.867−788.17
−1.833−777.06
−1.800−765.99
−1.767−754.97
−1.733−743.99
−1.700−733.06
−1.667−722.18
−1.633−711.36
−1.600−700.59
−1.567−689.88
−1.533−679.23
−1.500−668.65
−1.467−658.14
−1.433−647.71
−1.400−637.36
−1.367−627.09
−1.333−616.91
−1.300−606.83
−1.267−596.86
−1.233−586.99
−1.200−577.25
−1.167−567.63
−1.133−558.15
−1.100−548.82
−1.067−539.64
−1.033−530.63
−1−521.80
−0.9667−513.16
−0.9333−504.72
−0.9000−496.50
−0.8667−488.50
−0.8333−480.75
−0.8000−473.24
−0.7667−466.00
−0.7333−459.04
−0.7000−452.36
−0.6667−445.97
−0.6333−439.89
−0.6000−434.11
−0.5667−428.64
−0.5333−423.48
−0.5000−418.64
−0.4667−414.11
−0.4333−409.89
−0.4000−405.96
−0.3667−402.34
−0.3333−399.00
−0.3000−395.95
−0.2667−393.16
−0.2333−390.63
−0.2000−388.35
−0.1667−386.31
−0.1333−384.49
−0.1000−382.89
−0.0667−381.50
−0.0333−380.30

First 60 of 121 rows.

Likelihood-ratio tests

H₀χ²(1)p
λ = 1 (no transformation)56.889< .001
λ = 0 (log)5.361.021

Before and after (λ̂)

ScaleSkewness (G1)Shapiro–Wilk p
Original1.242< .001
Transformed (λ = 0.203)−0.0164.340
  • 37 of 153 rows were left out because a value was missing.
  • λ maximizes the profile log-likelihood of a normal model for the transformed values (as scipy.stats.boxcox / MASS::boxcox on an intercept-only model); the interval inverts the likelihood-ratio test.
  • Suggested λ: the interpretable value (−2, −1, −½, 0, ½, 1, 2) inside the interval closest to λ̂. Results on a transformed scale change the estimand — after a log, differences of means become ratios of geometric means.
Python

λ = 0.20, 95% CI [0.03, 0.39]

λ (maximum likelihood)
0.2034
95% CI (profile likelihood)
[0.0299, 0.3915]
Suggested λ
0.2000

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

Likelihood-ratio tests

H₀χ²(1)p
λ = 1 (no transformation)56.889< .001
λ = 0 (log)5.361.021

Before and after (λ̂)

ScaleSkewness (G1)Shapiro–Wilk p
Original1.242< .001
Transformed (λ = 0.203)−0.0164.340
  • 37 of 153 rows were left out because a value was missing.
  • λ maximizes the profile log-likelihood of a normal model for the transformed values (as scipy.stats.boxcox / MASS::boxcox on an intercept-only model); the interval inverts the likelihood-ratio test.
  • Suggested λ: the interpretable value (−2, −1, −½, 0, ½, 1, 2) inside the interval closest to λ̂. Results on a transformed scale change the estimand — after a log, differences of means become ratios of geometric means.

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

  • Ozone boxcoxairquality · variable: Ozone
  • Hp boxcox 90mtcars · variable: hp
  • Change yeojohnsons1_outliers · variable: change
  • Pulse shifteds1_survey · variable: pulse rate
  • Degenerate constantairquality · variable: Ozone
  • Degenerate n2airquality · variable: Ozone

In the guides

Where it sits in the decision guides

  • Normality (per group, differences or residuals) · Statistics Guide · Step 2 — Check assumptions
  • Remedies and sensitivity analyses · Statistics Guide · Step 3 — If assumptions are violated
  • Transformations · Statistics Guide · Step 3 — If assumptions are violated
  • Scaling and transformation: standardize, normalize, Box–Cox / Yeo–Johnson · DS & ML Decision Guide · Prepare data for modelling

What you need

Variablenumeric · 1 column
A numeric variable (Box–Cox needs positive values).

Choices you make

statistics

Transformation familydefault box-cox

Box–Cox needs positive values; Yeo–Johnson also works with zero and negative values.

  • Box–Cox (positive values)(default) — A power transform for positive values only; the classic choice.
  • Yeo–Johnson (any values) — Extends Box–Cox to zero and negative values; pick it when the column has any.
Confidence level (λ)default 0.95

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

options

Shift added before transformingdefault 0

A constant added to every value (e.g. to make Box–Cox possible with zeros); it changes λ.

What it reports

n
How many independent units the analysis used; it sets precision and power.
shift
The moment a series' level (mean) jumps — a relocated station, a new instrument, a policy taking effect.
lambda
Shrinks coefficients towards zero to reduce overfitting; lasso can drop predictors entirely.
lambda_ci_low
A range of effect values compatible with your data at the chosen confidence level.
lambda_ci_high
A range of effect values compatible with your data at the chosen confidence level.
lambda_rounded
Re-expressing a variable (log, square root, ranks) to reduce skew or stabilize variance.
llf
The logarithm of the likelihood; higher (less negative) means the model fits the data better.
lr_lambda1
Re-expressing a variable (log, square root, ranks) to reduce skew or stabilize variance.
p_lambda1
How surprising your data would be if the null hypothesis were true, as a probability.
lr_lambda0
Re-expressing a variable (log, square root, ranks) to reduce skew or stabilize variance.
p_lambda0
How surprising your data would be if the null hypothesis were true, as a probability.
skew_before
How lopsided a distribution is; positive skew has a long right tail.
skew_after
How lopsided a distribution is; positive skew has a long right tail.
sw_p_before
A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
sw_p_after
A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
includes_one
Re-expressing a variable (log, square root, ranks) to reduce skew or stabilize variance.
includes_zero
Re-expressing a variable (log, square root, ranks) to reduce skew or stabilize variance.
family_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.

Python and R

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

Default traps between the two languages

  • λ̂ and the interval ends are roots found by Brent's method in both engines (scipy brentq ↔ uniroot, tol 1e-14) from brackets found by fminbound ↔ optimize; observed agreement ~1e-13.
Python

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

# Power transformation (Box–Cox / Yeo–Johnson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method transform.power 1.0.2 · spec 9e352dfc34573ce7
# Dataset: airquality (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
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import describe as csd
from codesplash.stats import transform as cst

# %% Data
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=["Ozone"])
n_input = len(df)
df = df.dropna(subset=["Ozone"])  # listwise deletion over the analysis columns
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, ["Ozone"])  # infinite values stop the run (registry/errors.yaml)

# %% Fit λ
y = "Ozone"
family = "box-cox"  # "box-cox" needs positive values; "yeo-johnson" accepts any real values
shift = 0
conf = 0.95
x = df[y].to_numpy(dtype=float) + shift
n = x.size
cs.check_rows(n, 3, "A power transformation")  # needs at least three values
check_not_constant(x, y)  # one value: the profile likelihood of λ is undefined
if family == "box-cox" and np.any(x <= 0):
    cs.cs_error("CS_E_INVALID_VALUES", column=y, requirement="positive for Box–Cox (add a shift, or use Yeo–Johnson)",
                count=int(np.sum(x <= 0)))
fit = cst.fit(x, family, conf)  # λ̂ = root of the profile-likelihood derivative; profile-likelihood interval
lam = fit["lambda"]
t = cst.transform(x, lam, family)
llf_1 = cst.llf(x, 1.0, family)
llf_0 = cst.llf(x, 0.0, family)
lr_1 = 2 * (fit["llf"] - llf_1)  # H0: λ = 1 (no transformation needed)
lr_0 = 2 * (fit["llf"] - llf_0)  # H0: λ = 0 (log / log1p)


def sw(v):
    return float(stats.shapiro(v).pvalue) if 3 <= v.size <= 5000 and np.ptp(v) > 0 else None


# %% Result
label = "Box–Cox" if family == "box-cox" else "Yeo–Johnson"
values = {
    "n": n, "shift": shift, "lambda": lam, "lambda_ci_low": fit["ci_low"], "lambda_ci_high": fit["ci_high"],
    "lambda_rounded": fit["rounded"], "llf": fit["llf"],
    "lr_lambda1": lr_1, "p_lambda1": float(stats.chi2.sf(lr_1, 1)), "lr_lambda0": lr_0, "p_lambda0": float(stats.chi2.sf(lr_0, 1)),
    "skew_before": csd.moments(x)["skewness"], "skew_after": csd.moments(t)["skewness"],
    "sw_p_before": sw(x), "sw_p_after": sw(t),
    "includes_one": bool(fit["ci_low"] <= 1 <= fit["ci_high"]), "includes_zero": bool(fit["ci_low"] <= 0 <= fit["ci_high"]),
    "family_label": label,
}
rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
pct = f"{conf:.0%}"
# The profile the interval is read from, on a grid wide enough to show both limits and the usual λ values.
grid_lo, grid_hi = min(-2.0, fit["ci_low"] - 0.5), max(2.0, fit["ci_high"] + 0.5)
grid = np.linspace(grid_lo, grid_hi, 121)
profile = [cst.llf(x, float(g), family) for g in grid]
cs.publish({
    "method": "transform.power",
    "methodVersion": "1.0.2",
    "title": f"{label} transformation",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{label} λ for {y}: {lam:.3f}, {pct} CI [{fit['ci_low']:.3f}, {fit['ci_high']:.3f}]; suggested λ = {fit['rounded']:g}.",
    "apa": f"λ = {cs.fmt_num(lam)}, {pct} CI [{cs.fmt_num(fit['ci_low'])}, {cs.fmt_num(fit['ci_high'])}]",
    "statistics": [{"key": "lambda", "label": "λ (maximum likelihood)", "value": lam},
                   {"key": "ci", "label": f"{pct} CI (profile likelihood)", "value": [fit["ci_low"], fit["ci_high"]]},
                   {"key": "lambda_rounded", "label": "Suggested λ", "value": fit["rounded"]}],
    "tables": [
        {"key": "tests", "title": "Likelihood-ratio tests", "columns": [
            {"key": "h0", "label": "H₀", "type": "string"}, {"key": "lr", "label": "χ²(1)", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
         "rows": [{"h0": "λ = 1 (no transformation)", "lr": lr_1, "p": values["p_lambda1"]},
                  {"h0": "λ = 0 (log)" if family == "box-cox" else "λ = 0 (log1p for x ≥ 0)", "lr": lr_0, "p": values["p_lambda0"]}]},
        {"key": "shape", "title": "Before and after (λ̂)", "columns": [
            {"key": "scale", "label": "Scale", "type": "string"}, {"key": "skewness", "label": "Skewness (G1)", "type": "number"},
            {"key": "sw_p", "label": "Shapiro–Wilk p", "type": "pvalue"}],
         "rows": [{"scale": "Original", "skewness": values["skew_before"], "sw_p": values["sw_p_before"]},
                  {"scale": f"Transformed (λ = {lam:.3f})", "skewness": values["skew_after"], "sw_p": values["sw_p_after"]}]},
    ],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": [
        "λ maximizes the profile log-likelihood of a normal model for the transformed values (as scipy.stats.boxcox / MASS::boxcox on an intercept-only model); the interval inverts the likelihood-ratio test.",
        "Suggested λ: the interpretable value (−2, −1, −½, 0, ½, 1, 2) inside the interval closest to λ̂. Results on a transformed scale change the estimand — "
        "after a log, differences of means become ratios of geometric means.",
    ],
    "charts": [
        cs.chart("before", "histogram", f"{y} (original)", {"x": cs.col(y, x[rows])}),
        cs.chart("after", "histogram", f"{y} transformed (λ = {lam:.2f})", {"x": cs.col(f"{y} (λ = {lam:.2f})", t[rows])}),
        cs.chart("qq-after", "qq", "Normal Q–Q after transformation", {"x": cs.col(f"{y} (λ = {lam:.2f})", t[rows])}),
        cs.chart("profile", "boxcox-profile", f"Profile log-likelihood of λ ({label})",
                 {"lambda": cs.col("λ", grid, "numeric"), "loglik": cs.col("Profile log-likelihood", profile, "numeric")}, controls={"level": conf}),
    ],
    "values": values,
})
R

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

# Power transformation (Box–Cox / Yeo–Johnson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method transform.power 1.0.2 · spec 9e352dfc34573ce7
# Dataset: airquality (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/airquality.parquet", col_select = c("Ozone")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Ozone")]), , 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("Ozone"))  # infinite values stop the run (registry/errors.yaml)

# %% Fit lambda
y <- "Ozone"
family <- "box-cox"  # "box-cox" needs positive values; "yeo-johnson" accepts any real values
shift <- 0
conf <- 0.95
x <- as.numeric(df[[y]]) + shift
n <- length(x)
cs_check_rows(n, 3, "A power transformation")  # needs at least three values
cs_check_not_constant(x, y)  # one value: the profile likelihood of lambda is undefined
if (family == "box-cox" && any(x <= 0)) {
  cs_error("CS_E_INVALID_VALUES", column = y, requirement = "positive for Box–Cox (add a shift, or use Yeo–Johnson)",
           count = sum(x <= 0))
}
fit <- cs_power_fit(x, family, conf)  # root of the profile-likelihood derivative; profile-likelihood interval
lam <- fit$lambda
t <- cs_power_transform(x, lam, family)
llf_1 <- cs_power_llf(x, 1, family)
llf_0 <- cs_power_llf(x, 0, family)
lr_1 <- 2 * (fit$llf - llf_1)  # H0: lambda = 1 (no transformation needed)
lr_0 <- 2 * (fit$llf - llf_0)  # H0: lambda = 0 (log / log1p)
sw <- function(v) if (length(v) >= 3 && length(v) <= 5000 && diff(range(v)) > 0) shapiro.test(v)$p.value else NULL

# %% Result
label <- if (family == "box-cox") "Box–Cox" else "Yeo–Johnson"
values <- list(
  n = n, shift = shift, lambda = lam, lambda_ci_low = fit$ci_low, lambda_ci_high = fit$ci_high,
  lambda_rounded = fit$rounded, llf = fit$llf,
  lr_lambda1 = lr_1, p_lambda1 = pchisq(lr_1, 1, lower.tail = FALSE), lr_lambda0 = lr_0, p_lambda0 = pchisq(lr_0, 1, lower.tail = FALSE),
  skew_before = cs_moments(x)$skewness, skew_after = cs_moments(t)$skewness,
  sw_p_before = sw(x), sw_p_after = sw(t),
  includes_one = fit$ci_low <= 1 && 1 <= fit$ci_high, includes_zero = fit$ci_low <= 0 && 0 <= fit$ci_high,
  family_label = label
)
rows <- unique(round(seq(1, n, length.out = min(n, 5000))))
pct <- sprintf("%.0f%%", conf * 100)
tname <- sprintf("%s (λ = %.2f)", y, lam)
# The profile the interval is read from, on a grid wide enough to show both limits and the usual λ values.
grid <- seq(min(-2, fit$ci_low - 0.5), max(2, fit$ci_high + 0.5), length.out = 121)
profile <- vapply(grid, function(g) cs_power_llf(x, g, family), numeric(1))
cs_publish(list(
  method = "transform.power",
  methodVersion = "1.0.2",
  title = paste(label, "transformation"),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = sprintf("%s λ for %s: %.3f, %s CI [%.3f, %.3f]; suggested λ = %s.", label, y, lam, pct, fit$ci_low, fit$ci_high, format(fit$rounded)),
  apa = sprintf("λ = %s, %s CI [%s, %s]", cs_fmt_num(lam), pct, cs_fmt_num(fit$ci_low), cs_fmt_num(fit$ci_high)),
  statistics = list(list(key = "lambda", label = "λ (maximum likelihood)", value = lam),
                    list(key = "ci", label = paste(pct, "CI (profile likelihood)"), value = c(fit$ci_low, fit$ci_high)),
                    list(key = "lambda_rounded", label = "Suggested λ", value = fit$rounded)),
  tables = list(
    list(key = "tests", title = "Likelihood-ratio tests", columns = list(
      list(key = "h0", label = "H₀", type = "string"), list(key = "lr", label = "χ²(1)", type = "number"), list(key = "p", label = "p", type = "pvalue")),
      rows = list(list(h0 = "λ = 1 (no transformation)", lr = lr_1, p = values$p_lambda1),
                  list(h0 = if (family == "box-cox") "λ = 0 (log)" else "λ = 0 (log1p for x ≥ 0)", lr = lr_0, p = values$p_lambda0))),
    list(key = "shape", title = "Before and after (λ̂)", columns = list(
      list(key = "scale", label = "Scale", type = "string"), list(key = "skewness", label = "Skewness (G1)", type = "number"),
      list(key = "sw_p", label = "Shapiro–Wilk p", type = "pvalue")),
      rows = list(list(scale = "Original", skewness = values$skew_before, sw_p = values$sw_p_before),
                  list(scale = sprintf("Transformed (λ = %.3f)", lam), skewness = values$skew_after, sw_p = values$sw_p_after)))
  ),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = list(
    "λ maximizes the profile log-likelihood of a normal model for the transformed values (as scipy.stats.boxcox / MASS::boxcox on an intercept-only model); the interval inverts the likelihood-ratio test.",
    paste("Suggested λ: the interpretable value (−2, −1, −½, 0, ½, 1, 2) inside the interval closest to λ̂. Results on a transformed scale change the estimand —",
          "after a log, differences of means become ratios of geometric means.")
  ),
  charts = list(
    cs_chart("before", "histogram", sprintf("%s (original)", y), list(x = cs_col(y, x[rows]))),
    cs_chart("after", "histogram", sprintf("%s transformed (λ = %.2f)", y, lam), list(x = cs_col(tname, t[rows]))),
    cs_chart("qq-after", "qq", "Normal Q–Q after transformation", list(x = cs_col(tname, t[rows]))),
    cs_chart("profile", "boxcox-profile", sprintf("Profile log-likelihood of λ (%s)", label),
             list(lambda = cs_col("λ", grid, "numeric"), loglik = cs_col("Profile log-likelihood", profile, "numeric")), controls = list(level = conf))
  ),
  values = values
))

Sources

  • Box, G. E. P., & Cox, D. R. (1964). An analysis of transformations. JRSS B, 26, 211–252.
  • Yeo, I.-K., & Johnson, R. A. (2000). A new family of power transformations to improve normality or symmetry. Biometrika, 87, 954–959.

From the CodeSplash method registry · transform.power v1.0.2.