首页  >  文章  >  后端开发  >  如何重命名 Pandas DataFrame 的索引?

如何重命名 Pandas DataFrame 的索引?

Linda Hamilton
Linda Hamilton原创
2024-10-23 11:10:02740浏览

How to Rename the Index of a Pandas DataFrame?

重命名 Pandas DataFrame 的索引

使用 df.rename() 方法重命名 DataFrame 的列非常简单。但是,用户在尝试重命名索引时可能会遇到问题。本文将解决这个问题,并提供重命名索引的解决方案。

df.rename() 方法旨在接受指定新列名称的字典。然而,当重命名索引时,这种方法不适用。相反,要重命名索引,必须修改 index.names 属性,该属性是索引级别名称的列表。

例如,考虑具有 DateTime 索引且没有标头的 DataFrame:

<code class="python">import pandas as pd

df = pd.read_csv('data.csv', header=None, parse_dates=[[0]], index_col=[0])

# Attempt to rename the column using df.rename()
df.rename(columns={'1': 'SM'}, inplace=True)

# Print the resulting DataFrame
print(df.head())</code>

此代码将成功地将列重命名为“SM”,但索引保持不变。要重命名索引,我们可以使用以下代码:

<code class="python">df.index.names = ['Date']

# Print the resulting DataFrame
print(df.head())</code>

此代码将导致索引被重命名为“日期”:

                  SM
Date                  
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

以上是如何重命名 Pandas DataFrame 的索引?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn