How to Rename Pandas DataFrame Index Names?

Linda Hamilton
Release: 2024-10-23 11:38:32
Original
985 people have browsed it

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

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>
Copy after login
  1. Rename index value:
<code class="python">df1 = df.set_index('A')
df1.rename(index={1: 'a'})</code>
Copy after login
  1. Rename column name:
<code class="python">df1.rename(columns={'B': 'BB'})</code>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!