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

Python Pandas:DataFrame索引列标题无法保存至CSV文件

Fixing Missing Index Title in Saved CSV (Python 2.7, pandas 0.22)

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_label parameter: In pandas 0.22, setting index=True (the default) writes index values but not the index’s name as a header. Adding index_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 in pd.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:11:36