Home  >  Article  >  Backend Development  >  How to Rename the Index Name of a Pandas DataFrame?

How to Rename the Index Name of a Pandas DataFrame?

DDD
DDDOriginal
2024-10-23 13:17:01557browse

How to Rename the Index Name of a Pandas DataFrame?

How to Rename Pandas DataFrame Index

When working with Pandas DataFrames, it can be necessary to rename the index or column names for clarity or consistency. However, the df.rename() method has limitations when it comes to renaming the DataFrame index.

In the given example, the user attempted to rename the index and column name of a DataFrame using df.rename(), but only the column name was updated. This is because the rename() method takes a dictionary for the index, which applies to index values.

Instead, to rename the index level name, the following code should be used:

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

This assigns the name 'Date' to the index level.

It's important to remember that columns and index are both handled as objects of the same type (Index or MultiIndex). Therefore, you can interchange the two using the transpose method.

For a better understanding, consider the following examples:

<code class="python"># Create a DataFrame with named columns
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('ABC'))

# Rename the index
df.index.names = ['index']

# Rename the columns
df.columns.names = ['column']

print(df)  # Output:
# column  A  B  C
# index
# 0       1  2  3
# 1       4  5  6</code>

Note that the attribute for index names is just a list, and renaming can also be achieved using list comprehension or map.

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

Statement:
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