如何将NumPy数组形式的SARIMA预测结果添加到Pandas DataFrame?
Hey there! Let's work through this issue step by step to get your SARIMAX predictions properly integrated into your DataFrame, then handle the plotting and metric calculations.
1. Root Cause: Dimension Mismatch
The problem you're seeing almost always comes down to mismatched dimensions between your predictions array and the test DataFrame, or a 2D prediction array being treated as a single nested list by Pandas.
First, let's diagnose the shape of your data:
# Check the shape of your predictions and test DataFrame print("Predictions shape:", predictions.shape) print("Test DataFrame rows:", test.shape[0])
If predictions shows a 2D shape (like (1, 100) instead of (100,)), flatten it to a 1D array first:
predictions = predictions.flatten()
Then you can directly assign it to the DataFrame—no need to convert to a list (Pandas plays nicely with NumPy arrays):
test['predicted'] = predictions
Double-check your SARIMAX prediction parameters too! Make sure you're predicting exactly the length of your test set, e.g.:
# Example: Predict from the end of training data to end of test data predictions = model.predict(start=len(train), end=len(train)+len(test)-1)
2. Verify the New Column
After assignment, confirm everything looks right with:
print(test[['your_actual_value_column', 'predicted']].head())
You should see a separate prediction value for every row in the test set.
3. Plot Actual vs. Predicted Values
Use Matplotlib for a clean comparison plot—replace your_actual_value_column with your test set's true value column name:
import matplotlib.pyplot as plt plt.figure(figsize=(12, 6)) plt.plot(test['your_actual_value_column'], label='Actual Values', linewidth=2) plt.plot(test['predicted'], label='Predicted Values', linestyle='--', linewidth=2) plt.title('Time Series: Actual vs. SARIMAX Predictions') plt.xlabel('Date/Time') plt.ylabel('Value') plt.legend() plt.grid(alpha=0.3) plt.show()
4. Calculate MSE and RMSE Metrics
You can use scikit-learn's metrics module for this, or compute manually if you prefer:
Option 1: Using scikit-learn
from sklearn.metrics import mean_squared_error import numpy as np mse = mean_squared_error(test['your_actual_value_column'], test['predicted']) rmse = np.sqrt(mse) print(f"Mean Squared Error (MSE): {mse:.4f}") print(f"Root Mean Squared Error (RMSE): {rmse:.4f}")
Option 2: Manual Calculation
import numpy as np mse = ((test['your_actual_value_column'] - test['predicted']) ** 2).mean() rmse = np.sqrt(mse) print(f"MSE: {mse:.4f} | RMSE: {rmse:.4f}")
Quick Troubleshooting Checks
- Ensure your SARIMAX prediction window exactly matches the time range of your test set
- Confirm
predictionsis a 1D array (not nested) before assigning to the DataFrame - Make sure your test DataFrame has no missing rows that would throw off the length match
内容的提问来源于stack exchange,提问作者bbartling

