【问题标题】:sklearn TimeSeriesSplit Error: KeyError: '[ 0 1 2 ...] not in index'sklearn TimeSeriesSplit 错误:KeyError:'[0 1 2 ...] 不在索引中'
【发布时间】:2019-01-06 21:54:54
【问题描述】:

我想在以下数据帧上使用来自 sklearn 的 TimeSeriesSplit 来预测总和:

所以要准备 X 和 y,我执行以下操作:

X = df.drop(['sum'],axis=1)
y = df['sum']

然后将这两个喂给:

for train_index, test_index in tscv.split(X):
X_train01, X_test01 = X[train_index], X[test_index]
y_train01, y_test01 = y[train_index], y[test_index]

这样做,我得到以下错误:

KeyError: '[ 0  1  2 ...] not in index'

这里 X 是一个数据框,显然这会导致错误,因为如果我将 X 转换为数组,如下所示:

X = X.values

然后它将起作用。但是,为了以后对模型的评估,我需要 X 作为数据框。有什么方法可以将 X 保留为数据框并将其提供给 tscv 而无需将其转换为数组?

【问题讨论】:

  • 我对@9​​87654327@ 和tscv 对象的类型感到困惑。似乎您有一个时间索引,并且您正在尝试按整数选择索引。试试iloc

标签: pandas scikit-learn time-series sklearn-pandas train-test-split


【解决方案1】:

正如@Jarad 正确所说,如果您更新了 pandas 版本,它不会像以前的版本那样自动切换到基于整数的索引。您需要明确使用 .iloc 进行基于整数的切片。

for train_index, test_index in tscv.split(X):
    X_train01, X_test01 = X.iloc[train_index], X.iloc[test_index]
    y_train01, y_test01 = y.iloc[train_index], y.iloc[test_index]

https://pandas.pydata.org/pandas-docs/stable/indexing.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    相关资源
    最近更新 更多