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

Pandas IndexError问题:绘制实际与预测值时的索引错误

解决iloc索引错误:绘制能源负荷实际值与预测值对比图

错误原因

报错IndexError: DataFrame indexer is not allowed for .iloc的核心问题是:你试图用**整个DataFrame(X_test)**作为iloc的索引,但iloc仅支持整数位置、整数列表或切片这类索引方式,不能直接传入DataFrame对象。

train_test_split拆分数据后,X_test和y_test会保留原数据集的行索引,我们可以利用这个索引匹配对应的timestamp数据。

修复方案

将绘图代码中获取timestamp的方式,从data['timestamp'].iloc[X_test]改为通过X_test的索引标签获取,以下两种写法等价:

  • 使用X_test的索引:data['timestamp'].loc[X_test.index]
  • 使用y_test的索引(两者索引完全一致):data['timestamp'].loc[y_test.index]

修正后的完整代码

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

path = '/content/drive/MyDrive/ML_DATASETS/energy.csv'
data = pd.read_csv(path)

data['timestamp'] = pd.to_datetime(data['timestamp'])
data['time_num'] = range(len(data))

X = data[['time_num', 'temp']]
y = data['load']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = LinearRegression()
model.fit(X_train, y_train)

y_pred = model.predict(X_test)

plt.figure(figsize=(15, 5))
# 修正索引匹配逻辑
plt.scatter(data['timestamp'].loc[X_test.index], y_test, s=5, label="Actual")
plt.scatter(data['timestamp'].loc[X_test.index], y_pred, s=5, color='red', label="Predicted")
plt.xlabel("Datetime")
plt.ylabel("Load")
plt.title("Energy Load:Actual vs Predicted")
plt.legend()
plt.tight_layout()
plt.show()

额外说明

如果之前尝试用loc仍失败,大概率是直接传入了X_test而非X_test.index。loc接受的是索引标签,X_test本身是DataFrame而非索引对象,必须通过.index属性提取测试集对应的原数据索引标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 12:29:51