实现3个月简单移动平均预测时触发IndexError错误求助
修复3个月简单移动平均预测函数的IndexError问题
嘿,我一眼就看到你代码里的几个小问题,正是这些导致了IndexError,咱们一步步来修复:
问题1:错误的数组追加方式
你写的d=np.append(d[np.nan]*extra_periods)完全搞反了逻辑:
d[np.nan]试图用浮点数np.nan作为数组索引,numpy根本不允许这么做,这直接触发了索引错误- 正确的做法是先创建包含
extra_periods个np.nan的列表,再把它追加到原始需求数组后面,改成:d = np.append(d, [np.nan] * extra_periods)
问题2:额外周期预测的索引范围错误
原代码里f[cols+1:]=f[t]的索引不对:
cols是原始需求序列的长度,原始序列的索引是0到cols-1,额外周期是从cols索引开始的- 改成
f[cols:] = f[t]才能正确把最后一个历史预测值赋值给所有未来周期
问题3:循环范围的小调整(可选但更合理)
原循环for t in range(n, cols+1)里,当t=cols时,d[t-n:t]其实是取原始序列的最后n个值,但因为我们已经把数组扩展了,其实循环到cols-1就够了,最后一个历史预测值可以单独计算,让代码更清晰。
修正后的完整代码
import numpy as np import pandas as pd def moving_avg(d, extra_periods=1, n=3): # 将输入转换为numpy数组 d = np.array(d) # 历史周期长度 cols = len(d) # 向需求数组追加extra_periods个np.nan以覆盖未来周期 d = np.append(d, [np.nan] * extra_periods) # 定义预测数组,初始全为nan f = np.full(cols + extra_periods, np.nan) # 生成历史周期内的预测值:从第n个位置开始,基于前n个需求的均值 for t in range(n, cols): f[t] = np.mean(d[t-n:t]) # 计算最后一个历史预测值,用于填充所有额外周期 last_forecast = np.mean(d[cols-n:cols]) f[cols:] = last_forecast # 返回包含需求、预测和误差的DataFrame df = pd.DataFrame.from_dict({"Demand": d, "Forecast": f, "Error": d - f}) return df # 测试你的示例数据 d = [37,60,85,112,132,145,179,198,212,232] df = moving_avg(d, extra_periods=1, n=3) print(df)
运行这段代码后,你会得到正确的移动平均预测结果:最后一行的预测值是最后3个历史需求的均值(198+212+232)/3 = 214,完美符合预期。
内容的提问来源于stack exchange,提问作者krushna mohapatra
相关产品推荐
相关产品推荐

