Compute an exponentially weighted moving average of a pandas Series from a span
Quick Overview
Implement an exponentially weighted moving average on a pandas Series for a given span, where each output blends the previous smoothed value with the current input. It tests the EWMA recursion, how pandas seeds and weights the series, and keeping the index and float dtype intact.
Compute an exponentially weighted moving average of a pandas Series from a span
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `ewm_mean(s: pd.Series, span: int) -> pd.Series`, which returns the exponentially weighted moving average of `s` defined by the recursion
$$y_t = (1-\alpha)\, y_{t-1} + \alpha\, x_t, \qquad \alpha = \frac{2}{\text{span}+1}$$
seeded with $y_0 = x_0$, so the first output equals the first input.
The function must:
- Preserve the original index of `s`.
- Return float values.
Example:
```python
s = pd.Series([1.0, 2.0, 3.0])
ewm_mean(s, span=2)
# alpha = 2/3
# 0 1.000000
# 1 1.666667
# 2 2.555556
# dtype: float64
```
```hint Check the second output
Work out the second output of the example by hand and compare it with what your implementation returns. Two common EWMA conventions agree on the first output and differ from the second one onward.
```
### Constraints & Assumptions
- `span` is an integer of at least 1, so ${0 < \alpha \le 1}$.
- `s` holds numbers and may carry any index (dates, strings, non-contiguous integers).
- Assume no missing values for the main task. The follow-ups cover NaNs.
### What a Strong Answer Covers
- Matching the recursion exactly, including how the first output is seeded
- Keeping the input's index and returning float values
- The difference between the recursive form and the normalized weighted-average form of an EWMA
- Cost of the computation and behavior on edge inputs such as an empty or integer Series
### Follow-up Questions
- How does `adjust=True` differ from `adjust=False`, and when do the two agree?
- How would you handle NaNs in the input?
- How would you compute the EWMA separately for each user in a long table of daily values?
Overview: Implement an exponentially weighted moving average on a pandas Series for a given span, where each output blends the previous smoothed value with the current input. It tests the EWMA recursion, how pandas seeds and weights the series, and keeping the index and float dtype intact.