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
DataFrame Creation
Build DataFrames from dicts, lists, and files.
Indexing and Selecting
Select rows and columns with loc, iloc, and masks.
GroupBy Operations
Split, aggregate, and transform with groupby.
Merge and Join
Combine frames with merge and concat.
Pivot Tables
Reshape data with pivot, melt, and pivot_table.
Missing Data
Detect, fill, and drop NaN values.