import pandas as pd
df = pd.DataFrame({
'Price': [10, 11, 12, 13]
})
print(df.ewm(span=2).mean())
Expected Output:
Price
0 10.000000
1 10.750000
2 11.625000
3 12.541667
The DataFrame.ewm() (Exponentially Weighted Window) method provides exponentially weighted statistical functions, enabling exponential moving averages (EMA) and decay-weighted calculations for time series data. Unlike standard rolling() windows that assign equal weight to all observations within a fixed window and drop past values abruptly, ewm() assigns exponentially decreasing weights over time, giving more importance to recent observations while retaining long-term historical memory with decaying significance.
DataFrame.ewm(com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, times=None)span: Specifies decay in terms of span, $lpha = 2 / (span + 1)$.alpha: Direct smoothing factor $lpha$, $0 < lpha \le 1$.halflife: Specifies decay in terms of half-life.adjust: Boolean (default True). Divides by decaying adjustment factor in initial periods to account for unbalanced weighting..mean(), .std(), or .var().
Compute an EMA equivalent to a 3-period span.
import pandas as pd
df_prices = pd.DataFrame({
'Close': [100, 102, 101, 105, 107]
})
df_prices['EMA_3'] = df_prices['Close'].ewm(span=3).mean()
print(df_prices)
Q: What is the difference between rolling() and ewm()?
rolling() applies equal weights to a fixed number of recent rows. ewm() applies exponentially decaying weights across all historical data.
Explore interactive code cells, test EMA calculations, and execute self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.