To rename multiple index labels in a Pandas DataFrame, you can use the rename() method with the index parameter, providing a dictionary that maps the current index labels to the new labels. This allows you to change multiple index labels in one go.
Example of Renaming Multiple Indexes
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 multiple 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
- Creating the DataFrame: We create a DataFrame
dfwith default index labels (0, 1, 2). - Renaming Multiple Index Labels: The
rename()method is called with a dictionary in theindexparameter. The keys are the current index labels, and the values are the new labels you want to assign. - Output: The DataFrame
df_renamed_indexis printed, showing the new index labels 'index_1', 'index_2', and 'index_3'.
Important Note
- 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 theinplace=Trueparameter:
df.rename(index={0: 'index_1', 1: 'index_2', 2: 'index_3'}, inplace=True)
Further Learning
For more information on DataFrame operations, consider checking:
If you have any more questions or need additional examples, feel free to ask!
