Home  >  Article  >  Backend Development  >  How to Rename Pandas DataFrame Index Names?

How to Rename Pandas DataFrame Index Names?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 11:38:32929browse

How to Rename Pandas DataFrame Index Names?

Renaming Pandas DataFrame Index

This question pertains to renaming both the index and column names of a DataFrame. While the df.rename() method can modify column names, it faces difficulty when it comes to renaming the index.

The key to understanding this issue lies in the distinction between index values and index names. The df.rename() method operates on index values, while the desired operation involves modifying index names.

To successfully rename index names, utilize the following syntax:

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

For a more comprehensive understanding, consider the following examples:

  1. Rename index name:
<code class="python">df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('ABC'))
df.index.names = ['Date']</code>
  1. Rename index value:
<code class="python">df1 = df.set_index('A')
df1.rename(index={1: 'a'})</code>
  1. Rename column name:
<code class="python">df1.rename(columns={'B': 'BB'})</code>

It's crucial to note that index names are similar in concept to column names, as both are instances of the same object type (Index or MultiIndex). This equivalence allows for interchangeability between columns and index via transpose.

The above is the detailed content of How to Rename Pandas DataFrame Index Names?. 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