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

如何打印pandas Rolling滚动窗口内的具体数据内容

pandas Rolling对象查看窗口内具体数据实现方法

pandas中调用.rolling()方法返回的是Rolling窗口计算器对象,直接打印只会输出窗口的配置参数(也就是你看到的Rolling [window=180 D,min_periods=1,...]信息),不会返回窗口内存储的实际数据。要拿到DataFrame格式的窗口条目,可以用以下两种方式实现:

方法1:遍历捕获全量窗口,转成结构化DataFrame

如果需要拿到所有时间点对应的滚动窗口内容,可以通过自定义apply函数收集每个窗口的数据,最后转成DataFrame:

import pandas as pd

resampleStr = '180 D'
window_storage = {}

def get_window_data(window):
    # 以窗口截止时间的原数据索引为key
    window_end_idx = window.index[-1]
    window_storage[window_end_idx] = window.values
    # apply方法要求函数必须有返回值,随便返回一个占位值即可
    return 0

# 执行滚动计算触发窗口遍历
df['Close'].rolling(resampleStr).apply(get_window_data)

# 将存储的窗口数据转为DataFrame,每行对应一个截止时间点的180天窗口数据
window_result_df = pd.DataFrame.from_dict(window_storage, orient='index')
# 按需重命名列,比如t-0对应当前时间点的Close值,t-n对应n个周期前的Close值
window_result_df.columns = [f't-{len(window_result_df.columns)-1 - i}' for i in range(len(window_result_df.columns))]

注意:因为你使用的是180 D这种时间偏移窗口,不是固定行数窗口,不同时间点的窗口包含的样本数会因为非交易日、缺失值存在差异,转DataFrame时不足的位置会自动填充NaN。

方法2:提取单个指定窗口内容

如果只需要查看某一个时间点对应的窗口内容,不需要遍历全量数据,可以直接迭代Rolling对象取目标窗口,运行效率更高:

resampleStr = '180 D'
roller = df['Close'].rolling(resampleStr)

# 比如要查看原df中第200行位置对应的时间点的窗口内容
target_index_pos = 200
for pos, window_data in enumerate(roller):
    if pos == target_index_pos:
        # 单个窗口转为DataFrame格式
        single_window_df = window_data.to_frame()
        print(single_window_df)
        break

注意事项

  • 时间偏移类窗口不要用固定步长切片的方式取数据,因为每个窗口的样本数不固定,直接迭代Rolling对象是最稳妥的方式
  • 如果使用的是固定行数窗口(比如window=180),可以直接用列表推导式快速拿到全量窗口:all_window_list = [w.to_frame() for w in df['Close'].rolling(180)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 07:45:39