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

Python中如何基于给定DataFrame按超参数N生成特征选择用新DataFrame

实现方案

核心思路

本质是单变量时间序列的滑窗样本构造:每个样本包含前N个连续取值作为特征,第N+1个取值作为预测标签Y,直接调用pandas内置的rolling滑动窗口接口实现,无需手动编写索引循环,边界处理更可靠,大数据量场景下性能表现也更好。

完整代码实现

import pandas as pd

def generate_window_datasets(origin_df, max_N):
    close_ser = origin_df['close']
    # 遍历所有超参数取值生成对应数据集
    for n in range(1, max_N + 1):
        # 窗口长度设为N+1:前N个值为特征,最后1个为标签Y
        window_list = [w.tolist() for w in close_ser.rolling(n + 1) if len(w) == n + 1]
        # 构造列名
        col_names = [f'X{i}' for i in range(1, n+1)] + ['Y']
        result_df = pd.DataFrame(window_list, columns=col_names)
        # 若需要完全对齐你给出的N=1示例(不包含Y=6的行),可添加下一行代码
        # result_df = result_df.iloc[:-1, :]
        yield n, result_df

# 测试示例
if __name__ == '__main__':
    # 初始输入DataFrame
    origin_df = pd.DataFrame({'close': [1,2,3,4,5,6]})
    # 设定最大超参数取值
    max_super_param = 2
    # 遍历获取每个N对应的数据集
    for N, dataset in generate_window_datasets(origin_df, max_super_param):
        print(f'当前超参数N={N},生成的数据集为:')
        print(dataset, '\n')

输出效果

运行上述代码输出结果如下:

当前超参数N=1,生成的数据集为:
   X1  Y
0   1  2
1   2  3
2   3  4
3   4  5
4   5  6 

当前超参数N=2,生成的数据集为:
   X1  X2  Y
0   1   2  3
1   2   3  4
2   3   4  5
3   4   5  6 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:54:03