Python Pandas:DataFrame索引列标题无法保存至CSV文件
Hey there! Let's sort out this issue where your index title shows up when printing the DataFrame but doesn't save to the CSV file. The problem boils down to two small missteps in your original code: the order of operations, and a missing parameter critical for older pandas versions like 0.22.
What Went Wrong
First, you saved the CSV before renaming the index—so the updated title never made it into the file. Even if you fixed the order, pandas 0.22 doesn’t automatically write the index’s name as a column header in CSV files unless you explicitly specify it.
Corrected Code
Here’s the adjusted code that will preserve your index title in the CSV:
import pandas as pd # Read directly into a DataFrame (no need to wrap pd.read_csv in pd.DataFrame) df = pd.read_csv('test_set.csv') # Rename the index title first df.index.rename('indexTitle', inplace=True) # Save with index_label to ensure the title is written as the first column header df.to_csv('test_set2.csv', encoding='utf-8', index=True, index_label='indexTitle')
Key Changes Explained
- Order of operations: We rename the index before saving the CSV, so the change is applied when writing the file.
index_labelparameter: In pandas 0.22, settingindex=True(the default) writes index values but not the index’s name as a header. Addingindex_label='indexTitle'tells pandas to use that name as the column header for the index column in the CSV.- Simplified DataFrame creation:
pd.read_csv()already returns a DataFrame, so wrapping it inpd.DataFrame()is unnecessary (though harmless, it’s cleaner to skip).
After running this code, opening test_set2.csv will show the first column with the header indexTitle, matching what you see when printing the DataFrame.
内容的提问来源于stack exchange,提问作者Zap

