Skip to content

Transforming skewed data with Box–Cox and Yeo–Johnson

Find a power transformation for a skewed column, read its interval, and state what your result means on the new scale.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Read the λ, interval and before-and-after checks on a transform.power card
  • Choose between Box–Cox and Yeo–Johnson
  • State how a transformation changes what you are estimating

Read first

01

A family of powers

Read

A Box–CoxBox–Cox transformationRaises positive values to a power λ chosen from the data, with λ = 0 meaning the log, to make a skewed column more symmetric. transformation raises values to a power λ\lambda, with λ=0\lambda = 0 meaning the log:

y(λ)={(yλ−1)/λλ≠0log⁡yλ=0y^{(\lambda)} = \begin{cases} (y^\lambda - 1)/\lambda & \lambda \ne 0 \\ \log y & \lambda = 0 \end{cases}

λ=1\lambda = 1 changes nothing. Values below 1 pull in a long right tail, and values above 1 stretch one. Yeo–JohnsonYeo–Johnson transformationA power transformation like Box–Cox that also accepts zero and negative values. extends this to zero and negative values.

02

Ozone's skew

Predict

Predict first

Ozone readings are right-skewed, with skewness 1.24. Which λ\lambda will Box–Cox pick? (1 means leave alone, 0 means log.)

Make your guess between -1 and 2 λ, then reveal.

Reveal

λ=\lambda = 0.20, between a log and a square root. Skewness falls to −0.02.

03

Read the card

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

Three things to read:

  • The interval for λ\lambda runs from 0.03 to 0.39. It excludes 1, and narrowly excludes 0.
  • The suggested round value is 0.200.
  • The Shapiro–Wilk test moves from p < .001 to p = .340.
04

Try several

Explore

Try a log, a square root and a Box–Cox on data with different shapes.

AExplorable · The transformations workbench

Which transformation makes skewed data look normal, and what does Box–Cox suggest?

This data is right-skewed. Which simple transform will remove the most skew?

How sure?
0.90
120

Transform

0.50

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.

Prefer a value people can read. A log with an interval near 0 is easier to explain than λ=0.13\lambda = 0.13, and costs almost nothing.

05

What did you change?

Read

A transformation changes your question. A t test on log values compares geometric means, not means. A regression on log income describes percentage changes.

06

In a recipe

In the app

In Prepare (⌘3):

  • Power transform learns λ\lambda with Box–Cox or Yeo–Johnson.
  • Math transform applies a fixed function such as a log.
  • Rank or normal scores replaces values with ranks or normal scores, which removes all shape information.

A learned λ\lambda is a learned value, so a model needs it fitted on training rows.

07

In code

Read
Python
import pandas as pd
from scipy import stats

ozone = pd.read_csv("airquality.csv")["Ozone"].dropna()
transformed, lam = stats.boxcox(ozone)
print(lam)
R
library(MASS)

ozone <- na.omit(read.csv("airquality.csv")$Ozone)
profile <- boxcox(ozone ~ 1, lambda = seq(-1, 2, by = 0.01), plotit = FALSE)
profile$x[which.max(profile$y)]
08

Check your understanding

Checkpoint

Check yourself

A profit_change column contains negative values. Which transformation can you use directly?

Show the answer

Answer: b

Box–Cox and logs need positive values. You could add a shift, but the shift changes the result; Yeo–Johnson needs none.

Check yourself

What λ\lambda did Box–Cox estimate for ozone? Give two decimals.

Show the answer

Answer: 0.203389849603948

Read it from the card. It lies between a log (0) and a square root (0.5).

Check yourself

You run a t test on log-transformed incomes and find a difference. What have you compared?

Show the answer

Answer: b

The mean of logs back-transforms to a geometric mean, and differences on the log scale become ratios.

09

Recap

Recap
  • λ\lambda chooses the power; read its interval and prefer a value people can read.
  • Use Yeo–Johnson when values can be zero or negative.
  • A transformation changes what you are estimating, so say so.

Concepts in this lesson