How to rename index labels?

0208

To rename index labels in a Pandas DataFrame, you can use the rename() method with the index parameter. This allows you to specify which index labels to change and what their new labels should be.

Example of Renaming Index Labels

Here’s a step-by-step example:

import pandas as pd

# Create a sample DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Score': [85, 92, 78]
}

df = pd.DataFrame(data)

# Display the original DataFrame
print("Original DataFrame:")
print(df)

# Rename index labels
df_renamed_index = df.rename(index={0: 'index_1', 1: 'index_2', 2: 'index_3'})

# Display the DataFrame with renamed index labels
print("\nDataFrame with Renamed Index Labels:")
print(df_renamed_index)

Explanation

  1. Creating the DataFrame: We create a DataFrame df with default index labels (0, 1, 2).
  2. Renaming Index Labels: The rename() method is called with a dictionary in the index parameter. The keys are the current index labels, and the values are the new labels you want to assign.
  3. Output: The DataFrame df_renamed_index is printed, showing the new index labels 'index_1', 'index_2', and 'index_3'.

Important Note

  • Similar to renaming columns, the rename() method returns a new DataFrame with the updated index labels. If you want to modify the original DataFrame in place, you can use the inplace=True parameter:
df.rename(index={0: 'index_1', 1: 'index_2', 2: 'index_3'}, inplace=True)

Further Learning

For more information on DataFrame operations, you might find these resources helpful:

If you have any more questions or need additional examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!