skip to content

In pandas, how do `ewm(span=...)`, `ewm(halflife=...)` and `adjust` shape an exponentially weighted trend of daily web traffic?

level: seniorimportance: should knowfreq 30%

answer

  1. one decay parameter only
  2. span to alpha: 2 over s+1
  3. half the weight after h steps
  4. adjust normalises the early rows

basics

~20 s

span and halflife are two ways to set the decay alpha (2/(span+1), or the weight halving every halflife rows); pass exactly one. adjust=True, the default, normalises weights over the available history; adjust=False uses the recursive form starting from the first value.

solid answer

~30 s

`ewm` takes exactly one of `com`, `span`, `halflife` or `alpha`; passing two raises `ValueError` saying they are mutually exclusive. `span=7` gives `alpha = 2/(7+1) = 0.25`, the usual "7-day EWMA"; `halflife=3` makes an observation's weight halve every 3 rows. With the default `adjust=True` the mean divides by the sum of the weights actually present, so early values are proper weighted averages; `adjust=False` uses `y_t = alpha*x_t + (1-alpha)*y_(t-1)` from `y_0 = x_0`, which leans on the first value. Without `times`, decay is per row, not per day, so gaps distort it; `halflife='3 days'` with `times=` makes it time-aware, for `mean()` only.

code

python · 15 lines
python
import pandas as pd

daily = pd.Series(
    [1000, 1100, 1050, 3000, 1080, 1120, 1090, 1150],
    index=pd.date_range("2026-03-02", periods=8, freq="D"),
    name="visits",
)
trend = pd.DataFrame({
    "visits": daily,
    "span7": daily.ewm(span=7).mean(),                  # alpha = 0.25
    "span7_rec": daily.ewm(span=7, adjust=False).mean(),
    "half3": daily.ewm(halflife=3).mean(),              # halves every 3 rows
    "roll7": daily.rolling(7).mean(),
})
print(trend.round(1))

go deeper

for a junior

Recall that ewm gives recent rows more weight and that span=7 is the usual 7-day exponentially weighted average.

for a middle

Explain the span, com, halflife and alpha conversions, that only one may be passed, and what adjust does to the first rows.

for a senior

Choose the decay and adjust deliberately, set min_periods to hide the warm-up, and use times with a timedelta half-life when days are missing.

for a principal

Decide whether a trend metric should be exponential or a fixed window, and document its decay so dashboards and models reproduce the same number.

## What an exponentially weighted window is `Series.ewm` and `DataFrame.ewm` return an `ExponentialMovingWindow`. Like an expanding window it covers all history up to each row, but older observations get **geometrically smaller weights**. With smoothing factor `alpha` (between 0 and 1), the observation `i` rows back gets weight `(1 - alpha)^i`. The result reacts to a traffic spike immediately and lets it fade, instead of holding it at full weight for seven rows and then dropping it, which is what `rolling(7).mean()` does. ## Four ways to set the decay: pick one You must pass exactly one of these; two or more raise `ValueError: comass, span, halflife, and alpha are mutually exclusive`. | parameter | conversion to `alpha` | reads as | |---|---|---| | `span=s` (s >= 1) | `alpha = 2 / (s + 1)` | "an s-day EW moving average" | | `com=c` (c >= 0) | `alpha = 1 / (1 + c)` | centre of mass, `c = (s - 1) / 2` | | `halflife=h` (h > 0) | `alpha = 1 - exp(log(0.5) / h)` | weight halves every h rows | | `alpha=a` | used directly | the smoothing factor itself | For daily traffic: - `span=7` gives `alpha = 0.25`, the conventional pairing for a 7-day moving average. - `halflife=3` gives `alpha` of about 0.206: yesterday counts about 0.79 of today, three days ago half. - A larger span or half-life means a smoother, slower trend. ## `adjust`: how the early rows are weighted Real series have a start, and the two variants treat it differently: 1. **`adjust=True`** (default) divides by the sum of the weights that exist: `y_t = (x_t + (1-alpha) x_(t-1) + ... + (1-alpha)^t x_0) / (1 + (1-alpha) + ... + (1-alpha)^t)`. Each early value is a genuine weighted average of what has been seen. 2. **`adjust=False`** uses the recursion `y_0 = x_0`, `y_t = alpha * x_t + (1 - alpha) * y_(t-1)`. It treats the first value as if it summarised an infinite past, so the first observation dominates the early trend. With `span=7` and traffic starting 1000, 1100, the second value is about **1057** with `adjust=True` (1850 / 1.75) and **1025** with `adjust=False` (0.25 x 1100 + 0.75 x 1000). On a long series the two converge; on a short one, or right after a restart, they differ noticeably. `adjust=False` matches the textbook recursive EWMA and is what you want when reproducing a value computed incrementally elsewhere. ## Other arguments that change the numbers - **`min_periods`** defaults to `0`, so a value appears from the first row. Raise it to hide the warm-up, for example `min_periods=7`. - **`ignore_na`** defaults to `False`: weights follow absolute positions, so a `NaN` day still ages the values before it. With `ignore_na=True` the missing row is skipped as if it were not there. - **`times`** with a timedelta `halflife`: `daily.ewm(halflife='3 days', times=daily.index).mean()` decays by elapsed **time** rather than by rows, which is right for irregular or gappy data. `times` must be a datetime column or array of the same length; this mode supports only `mean()`, and a string or `Timedelta` half-life without `times` raises `ValueError`. ## EWM next to rolling and expanding | window | weights | starts reporting | |---|---|---| | `rolling(7)` | equal over the last 7 rows, then zero | after 7 rows (default) | | `expanding()` | equal over all rows so far | from the first row | | `ewm(span=7)` | geometric decay over all rows so far | from the first row | `expanding()` equals `rolling(window=len(s), min_periods=1)`, the equal-weight limit of the same idea. Unlike `rolling`, `ewm` takes no `'7D'` window string; time-awareness comes only through `times`. ## Reading the worked example In the snippet below a one-day spike of 3,000 visits sits among values near 1,100: - `roll7` stays `NaN` for six rows, then carries the spike at a fixed weight of one seventh for as long as it sits inside the window. - `span7` jumps on the spike day, and the spike's weight then shrinks by a factor of 0.75 with each later row, so its influence fades smoothly. - `half3` reacts a little less, since its `alpha` is about 0.206, and its spike weight halves every three rows. - `span7_rec` starts lower on the second row than `span7`, because `adjust=False` lets the first value dominate. ## Per-group trends `df.groupby('site')['visits'].ewm(span=7).mean()` computes a separate trend per site and returns a `MultiIndex` of the site and the original row label, just as `groupby().rolling()` does. Sort each group by time first: the weights follow row order.

  • Daily traffic has missing days. Why is `ewm(halflife=3)` misleading there, and what fixes it?
    Without `times`, decay is counted in rows, so the value before a three-day gap is treated as one day old. Pass the timestamps: `daily.ewm(halflife='3 days', times=daily.index).mean()` decays by elapsed time. That mode supports only `mean()`, and the half-life must be a timedelta-like value.
  • When would you choose `adjust=False` over the default?
    When you must match a recursive EWMA computed incrementally, for example a value updated as `alpha*x + (1-alpha)*previous` in a streaming job, or a formula from a spec. `adjust=False` reproduces that recursion from `y_0 = x_0`. For analysis on finite history the default `adjust=True` gives better-behaved early values.

  • You can pass span and halflife together to fine-tune the decay
  • span=7 only looks at the last seven rows
  • halflife=3 means three calendar days even without times
  • adjust=False is the default and starts from the first value
  • ewm accepts a '7D' window string like rolling