Pandas IndexError报错解决:使用Matplotlib绘制实际值与预测值时的索引问题
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.indexretains the original row labels from yourdataDataFrame that were assigned to the test set..locuses these labels to fetch the exacttimestampvalues that match youry_testandy_preddata points, ensuring proper alignment for your plot.
内容的提问来源于stack exchange,提问作者Rima 123

