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

Python3.9中使用NumPy重塑数据集报KeyError: range(0,20)如何解决

报错原因

你传入的uni_data是pandas的Series类型,这类数据结构在使用[]直接传入range对象取值时,会默认查找索引标签而非行的位置编号,你的Series索引中不存在range(0,20)这个标签值,因此抛出KeyError。

修复方案

两种可选方案均可解决问题:

  • 方案1:修改函数内的索引方式,改用.iloc按位置取值,适配pandas类型的输入
    修改后的函数代码如下:
def univariate_data(dataset, start_index, end_index, history_size, target_size):
    data = []
    labels = []
    start_index = start_index + history_size
    if end_index is None:
        end_index = len(dataset) - target_size

    for i in range(start_index, end_index):
        indices = range(i-history_size, i)
        # 改用iloc按位置取数,适配pandas Series/DataFrame输入
        data.append(np.reshape(dataset.iloc[indices], (history_size, 1)))
        labels.append(dataset.iloc[i+target_size])
    return np.array(data), np.array(labels)
  • 方案2:调用函数时直接传入numpy数组而非pandas对象,numpy原生支持range对象作为索引
    调用代码修改如下:
x_train_uni, y_train_uni = univariate_data(uni_data.values, 0, TRAIN_SPLIT,
                                           univariate_past_history,
                                           univariate_future_target)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:15:04