We use exponential moving average to smooth data and see trends better by giving more importance to recent values.
ewm() for exponential moving average in Pandas
DataFrame.ewm(span=None, com=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0).mean()
You choose one of span, com, halflife, or alpha to set how fast the weights decrease.
The mean() function calculates the exponential moving average after setting up the weights.
df['EMA'] = df['value'].ewm(span=3).mean()
df['EMA'] = df['value'].ewm(halflife=2).mean()
df['EMA'] = df['value'].ewm(alpha=0.5).mean()
This code creates a simple data table with values. Then it calculates the exponential moving average with a span of 3, which means recent values count more. Finally, it prints the table showing original and smoothed values.
import pandas as pd data = {'value': [10, 20, 15, 25, 30, 20, 40]} df = pd.DataFrame(data) # Calculate EMA with span=3 df['EMA'] = df['value'].ewm(span=3).mean() print(df)
EMA reacts faster to recent changes than simple moving average.
Choosing span or halflife depends on how quickly you want to react to new data.
Set min_periods to control how many points are needed before calculating EMA.
Exponential moving average smooths data by weighting recent points more.
Use ewm() with parameters like span to set smoothing speed.
Call mean() after ewm() to get the EMA values.