rolling() 是 Pandas 中用于移动窗口操作的强大函数,常用于:
- 计算滚动平均、最大值、最小值、求和等
- 时间序列平滑
- 统计窗口内的自定义聚合
python
df.rolling(window, min_periods=1).agg_func()
🎯 常见参数
参数 | 说明 |
---|---|
window |
滚动窗口大小(整数或时间窗口) |
min_periods |
最少有多少个非 NA 才计算结果(默认等于 window ) |
center |
是否将窗口对齐中心(默认靠右) |
win_type |
滚动权重类型,如 boxcar 、triang 、gaussian (默认 None) |
常见示例
📌 1. 计算滚动平均(window=3)
python
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5])
s.rolling(window=3).mean()
📌 2. 自定义滚动函数(如统计 "1" 出现次数)
python
import pandas as pd
# 示例数据
df = pd.DataFrame({
'flag': ['1', '0', '1', '1', '0', '1', '0', '0']
})
# 将 '1' 映射为整数 1,其他为 0
df['is_1'] = df['flag'].apply(lambda x: 1 if x == '1' else 0)
# 使用 rolling().sum() 计算过去3行中 '1' 的个数
df['count_last_3'] = df['is_1'].rolling(window=3, min_periods=1).sum()
print(df)
- rolling(window=3):以当前行为结尾,向前看 3 行
- min_periods=1:窗口最小长度为 1,防止前几行 NaN
- sum():因为我们把 '1' 转成了数字 1
📌 3. 与时间序列结合
python
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
# 时间窗口滚动:过去7天内平均值
df['rolling_avg'] = df['value'].rolling('7D').mean()
✅ 常用聚合函数
函数 | 含义 |
---|---|
.mean() |
均值 |
.sum() |
总和 |
.max() |
最大值 |
.min() |
最小值 |
.std() |
标准差 |
.var() |
方差 |
.count() |
非 NA 个数 |
.apply(func) |
自定义函数 |