Skip to main content
 首页 » 编程设计

python之无法重命名 pandas DataFrame 中的第一列

2025年05月04日21lori

多年来一直使用 pandas,但从未见过这种行为。我使用版本 0.18.1。我有一个包含以下内容的 .csv 文件:

id;foo;bar 
100001;11-22;spam 
100002;22-33;spamspam 

我正在将它读入 DataFrame:

pd.read_csv(csv_path, sep=';', index_col=False, encoding='UTF-8') 

这是我得到的:

      id    foo       bar 
0  100001  11-22      spam 
1  100002  22-33  spamspam 

现在我想将 id 字段重命名为 new_id:

df.rename(index=str, columns={'id': 'new_id'}, inplace=True) 

但是,它使 id 列具有相同的名称。

id 列出现在 df.columns 中:

df.columns 
Index([u'id', u'foo', u'bar'], dtype='object') 

它的索引是:

df.index 
Index([u'0', u'1'], dtype='object') 

尝试重命名 foo 或 bar 列按预期工作:

df.rename(index=str, columns={'foo': 'new_foo'}, inplace=True) 
 
      id new_foo       bar 
0  100001   11-22      spam 
1  100002   22-33  spamspam 

我认为 id 关键字可能有一些特殊之处,但是通过将 id 列重命名为其他名称可以观察到相同的行为。 如何重命名数据框中的第一列?

请您参考如下方法:

看起来像个奇怪的错误,你可以分配新的列名:

df.columns = ['new_id'] + df.columns.tolist()[1:] 
print (df) 
   new_id    foo       bar 
0  100001  11-22      spam 
1  100002  22-33  spamspam 

在 pandas 0.23.4 rename 中使用 id 效果很好。

如果 BOM 有问题,已在 pandas 0.19.0 中解决.

可能的解决方案是在您的 pandas 版本中更改 encoding:

df = csv_path, sep=';', index_col=False, encoding='UTF-16')