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

Pandas IndexError报错解决:使用Matplotlib绘制实际值与预测值时的索引问题

Fixing IndexError: DataFrame indexer is not allowed for .iloc in Your Matplotlib Plot

Let's break down what's causing this error and how to fix it quickly.

The Root Cause

Your error happens because you're passing the entire X_test DataFrame to .iloc in these lines:

plt.scatter(data['timestamp'].iloc[X_test], y_test, s=5,label="Actual")
plt.scatter(data['timestamp'].iloc[X_test], y_pred, s=5, color='red', label="Predicted")

.iloc only accepts integer positions, lists/arrays of integers, or boolean arrays—it can't handle a full DataFrame as an indexer. Luckily, train_test_split preserves the original index from your data DataFrame, so X_test.index already holds the exact row labels you need to fetch the corresponding timestamps.

The Fix

Replace .iloc[X_test] with .loc[X_test.index] in your scatter plot lines. This uses the original index labels to pull the correct timestamp values that align with your test data. Here's the corrected snippet:

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")

Full Corrected Code

Here's your complete code with the fix applied:

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))
# Fixed indexer to use X_test's original row labels
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()

Why This Works

  • X_test.index retains the original row labels from your data DataFrame that were assigned to the test set.
  • .loc uses these labels to fetch the exact timestamp values that match your y_test and y_pred data points, ensuring proper alignment for your plot.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 06:38:54