df = pd.DataFrame({"x": [1.0, 10.0, 100.0, 1000.0]})
df| x | |
|---|---|
| 0 | 1.0 |
| 1 | 10.0 |
| 2 | 100.0 |
| 3 | 1000.0 |
Take the logarithm of numeric columns.
Usage
Each selected column x is replaced by log(x + offset) / log(base).
For a transform that handles skew without any domain restriction, see StepOrderNorm.
A value equal to -offset becomes -inf and anything smaller becomes NaN. These pass through with a warning naming the columns, at both fit and transform time. A positive offset brings zeros into the domain.
signed=True suits columns that span zero. It computes sign(x) * log(|x|) with |x| < 1 flattened to 0, so every real value is valid and the result is continuous through the origin, but flat between -1 and 1. It does not use offset, so passing both is an error.
See Logarithms in Feature Engineering A to Z for background on this technique. See Arguments shared across steps for the arguments this step shares with the others.
columns: SelectorColumns to log-transform. Accepts a single column name, a list of names, a mlfeatures selector such as Selectors.numeric_features() (see Selectors for the full set), or a narwhals or polars selector (narwhals.selectors.numeric(), polars.selectors.numeric()). Selectors are resolved against the data frame’s schema when the recipe is fitted, so the same selector works on any backend. Only numeric columns are meaningful here.
base: float = math.e
Base of the logarithm; must be positive and not 1. Defaults to math.e (the natural logarithm).
offset: float = 0.0Added to every value before the logarithm. Defaults to 0.0. Cannot be combined with signed.
signed: bool = FalseWhether to use the signed formula described above instead of the plain logarithm. Defaults to False.
id: str | None = None"log"; a second step of this type in the same recipe becomes "log_2", and passing an id already used in the recipe is an error.
Each selected column is replaced by its logarithm:
Specifying the step touches no data:
Recipe (untrained)
Inputs: no roles assigned
Steps:
step_log(select(role='feature', type=NumericType)) [untrained]
There is nothing to estimate, so fit() only resolves the selection:
Recipe (trained)
Inputs: 1 columns (1 feature)
Steps:
step_log(x) [trained]
transform() takes the natural logarithm:
base changes the logarithm’s base, here to the base-10 logarithm:
| x | |
|---|---|
| 0 | 0.0 |
| 1 | 1.0 |
| 2 | 2.0 |
| 3 | 3.0 |
Zeros are outside the logarithm’s domain:
offset shifts every value up first, which brings them back in:
| x | |
|---|---|
| 0 | 0.000000 |
| 1 | 0.693147 |
| 2 | 1.386294 |
| 3 | 2.079442 |
A column spanning zero has negatives too:
| x | |
|---|---|
| 0 | -100.0 |
| 1 | -1.0 |
| 2 | 0.0 |
| 3 | 1.0 |
| 4 | 100.0 |
signed logs each side separately and flattens the middle: