0
0
Pandasdata~5 mins

ewm() for exponential moving average in Pandas

Choose your learning style9 modes available
Introduction

We use exponential moving average to smooth data and see trends better by giving more importance to recent values.

To track stock prices and see recent trends clearly.
To smooth noisy sensor data for better analysis.
To monitor website traffic changes over time.
To analyze sales data focusing on recent months.
To detect changes in temperature readings quickly.
Syntax
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.

Examples
Calculate EMA giving more weight to last 3 periods.
Pandas
df['EMA'] = df['value'].ewm(span=3).mean()
Calculate EMA where weights halve every 2 periods.
Pandas
df['EMA'] = df['value'].ewm(halflife=2).mean()
Calculate EMA with a fixed smoothing factor of 0.5.
Pandas
df['EMA'] = df['value'].ewm(alpha=0.5).mean()
Sample Program

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.

Pandas
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)
OutputSuccess
Important Notes

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.

Summary

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.