Python rolling计算“1”在过去3行中出现的次数

rolling() 是 Pandas 中用于移动窗口操作的强大函数,常用于:

  • 计算滚动平均、最大值、最小值、求和等
  • 时间序列平滑
  • 统计窗口内的自定义聚合
python 复制代码
df.rolling(window, min_periods=1).agg_func()

🎯 常见参数

参数 说明
window 滚动窗口大小(整数或时间窗口)
min_periods 最少有多少个非 NA 才计算结果(默认等于 window
center 是否将窗口对齐中心(默认靠右)
win_type 滚动权重类型,如 boxcartrianggaussian(默认 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) 自定义函数
相关推荐
没有梦想的咸鱼185-1037-166318 分钟前
基于R语言机器学习方法在生态经济学领域中的实践技术应用
开发语言·机器学习·数据分析·r语言
2401_8288906421 分钟前
使用 BERT 实现意图理解和实体识别
人工智能·python·自然语言处理·bert·transformer
向上的车轮43 分钟前
基于go语言的云原生TodoList Demo 项目,验证云原生核心特性
开发语言·云原生·golang
The Chosen One98544 分钟前
C++ : AVL树-详解
开发语言·c++
PH_modest1 小时前
【Qt跬步积累】—— 初识Qt
开发语言·qt
怀旧,1 小时前
【C++】18. 红⿊树实现
开发语言·c++
多恩Stone2 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
xiaopengbc2 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@2 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫