Skip to content
Pandas

Time Series

Resample, shift, and roll windows over time data.

By EZ4Code Team
time-seriesresamplerolling

Code

import pandas as pd
import numpy as np

idx = pd.date_range("2024-01-01", periods=10, freq="D")
ts = pd.Series(np.random.rand(10), index=idx)

# Resample to weekly mean
weekly = ts.resample("W").mean()

# Rolling window
ma3 = ts.rolling(window=3).mean()

# Shift for lag features
diff = ts - ts.shift(1)
pct = ts.pct_change()

# Time-based indexing
subset = ts["2024-01-03":"2024-01-06"]

# Timezone conversion
tz = ts.tz_localize("UTC").tz_convert("Asia/Shanghai")
print(weekly, ma3, subset)

Explanation

A DatetimeIndex enables time-based slicing and resampling to a different frequency such as weekly means. rolling computes moving-window statistics, and shift creates lagged series for diff or percent-change calculations. tz_localize and tz_convert move series between time zones.

More Pandas Snippets