You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何遍历DataFrame,每次获取大小为3的滑动窗口Rank列值?

实现代码

前置准备:构造测试DataFrame

import pandas as pd

df = pd.DataFrame({
    "Name": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
    "Rank": [2, 3, 6, 7, 4, 3, 9, 2, 5]
})

方法1:使用pandas rolling 方法(推荐)

直接调用pandas内置的滑动窗口接口实现,代码简洁性能高:

window_len = 3
# 提取所有长度为3的滑动窗口
result = [w.tolist() for w in df["Rank"].rolling(window_len) if len(w) == window_len]

# 按需求打印每个窗口的内容
for i, window in enumerate(result, 1):
    print(f"第{i}次提取结果:")
    for num in window:
        print(num)

方法2:纯循环实现

不需要依赖pandas的内置接口,用基础索引切片实现:

window_len = 3
rank_values = df["Rank"].tolist()
result = []
# 遍历所有合法的窗口起始位置
for start in range(len(rank_values) - window_len + 1):
    result.append(rank_values[start: start + window_len])

两种方法得到的结果完全一致,result列表存储了所有提取到的滑动窗口,内容为:
[[2,3,6], [3,6,7], [6,7,4], [7,4,3], [4,3,9], [3,9,2], [9,2,5]]


内容的提问来源于stack exchange,提问作者Krishna Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:27:02