Python 3.5.x机器学习完成后,如何用Pandas/CSV库保存预测结果至CSV?
Hey there! After wrapping up your machine learning model, saving those predictions to a CSV is straightforward with either Pandas or Python's built-in CSV library. Let's walk through both methods tailored specifically for Python 3.5.x.
Using Pandas
First, a quick heads-up: Python 3.5.x is only compatible with Pandas versions up to 0.25.3 (the last release that supports Python 3.5). If you haven't installed Pandas yet, grab the compatible version with this command:
pip install pandas==0.25.3
Here's a step-by-step example to save your predictions:
- Assume your model's output is stored in a NumPy array or list (e.g.,
predictions = model.predict(X_test)). - Convert the predictions into a Pandas DataFrame—you can also include extra metadata like sample IDs if you need to map predictions back to original data.
- Use the
to_csv()method to write the DataFrame to a CSV file.
Sample code:
import pandas as pd import numpy as np # Replace this with your actual model predictions predictions = np.array([0, 1, 0, 1, 1]) # Optional: add sample IDs to track which prediction belongs to which data point test_sample_ids = [1001, 1002, 1003, 1004, 1005] # Create a DataFrame with meaningful column names prediction_df = pd.DataFrame({ 'Sample_ID': test_sample_ids, 'Predicted_Class': predictions }) # Save to CSV—set index=False to skip writing the default Pandas index column prediction_df.to_csv('model_predictions.csv', index=False, encoding='utf-8')
Key notes for Python 3.5.x:
- The
encodingparameter works reliably here if you need to handle non-ASCII characters. - If your predictions are multi-dimensional (like class probabilities for multiple classes), the DataFrame will automatically split them into separate columns.
Using Python's Built-in CSV Library
If you prefer a lightweight, no-install option, Python's built-in csv module is perfect—it comes pre-packaged with Python 3.5.x, so no extra setup is needed.
Example code for basic predictions:
import csv import numpy as np # Replace with your model's actual output predictions = np.array([0, 1, 0, 1, 1]) test_sample_ids = [1001, 1002, 1003, 1004, 1005] # Open the CSV file in write mode—newline='' prevents extra blank lines (a Python 3 feature that works in 3.5) with open('model_predictions.csv', 'w', newline='', encoding='utf-8') as csv_file: # Create a CSV writer object csv_writer = csv.writer(csv_file) # Write the header row to label your columns csv_writer.writerow(['Sample_ID', 'Predicted_Class']) # Loop through your data and write each row for sample_id, pred in zip(test_sample_ids, predictions): csv_writer.writerow([sample_id, pred])
For multi-dimensional predictions (like class probabilities), you can flatten each entry to fit into a CSV row:
# Example: 3-class probability predictions prob_predictions = np.array([[0.1, 0.8, 0.1], [0.9, 0.05, 0.05]]) with open('probability_predictions.csv', 'w', newline='', encoding='utf-8') as csv_file: csv_writer = csv.writer(csv_file) # Header for probability columns csv_writer.writerow(['Sample_ID', 'Class_0_Prob', 'Class_1_Prob', 'Class_2_Prob']) for sample_id, prob_set in zip(test_sample_ids[:2], prob_predictions): # Convert the numpy array to a list and prepend the sample ID csv_writer.writerow([sample_id] + list(prob_set))
Quick Compatibility Check for Python 3.5.x
- Pandas: Always use versions ≤0.25.3 to avoid installation or runtime errors.
- CSV Module: It's part of Python's standard library, so no version conflicts—this code will work exactly as written.
内容的提问来源于stack exchange,提问作者Adarsh C

