Home > Backend Development > Python Tutorial > How to Rename the Index of a Pandas DataFrame?

How to Rename the Index of a Pandas DataFrame?

Linda Hamilton
Release: 2024-10-23 11:10:02
Original
831 people have browsed it

How to Rename the Index of a Pandas DataFrame?

Renaming Index of a Pandas DataFrame

Renaming the columns of a DataFrame is straightforward using the df.rename() method. However, users may encounter issues when attempting to rename the index. This article will address this problem and provide a solution for renaming the index.

The df.rename() method is designed to accept a dictionary specifying the new column names. However, this approach is not applicable when renaming the index. Instead, to rename the index, one must modify the index.names attribute, which is a list of the index level names.

For example, consider a DataFrame with a DateTime index and no header:

<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>
Copy after login

This code will successfully rename the column to 'SM' but will leave the index unchanged. To rename the index, we can use the following code:

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

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

This code will result in the index being renamed to 'Date':

                  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
Copy after login

The above is the detailed content of How to Rename the Index of a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template