To rename multiple columns at once in a Pandas DataFrame, you can use the rename() method with a dictionary that maps the current column names to the new names. This allows you to specify all the changes in a single call.
Example of Renaming Multiple Columns
Here’s a step-by-step example:
import pandas as pd
# Create a sample DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Score': [85, 92, 78],
'Age': [20, 21, 19]
}
df = pd.DataFrame(data)
# Display the original DataFrame
print("Original DataFrame:")
print(df)
# Rename multiple columns at once
df_renamed = df.rename(columns={
'Name': 'First Name',
'Score': 'Test Score',
'Age': 'Student Age'
})
# Display the renamed DataFrame
print("\nRenamed DataFrame:")
print(df_renamed)
Explanation
- Creating the DataFrame: We create a DataFrame
dfwith columns 'Name', 'Score', and 'Age'. - Renaming Columns: The
rename()method is called with a dictionary in thecolumnsparameter. Each key-value pair in the dictionary represents the current column name (key) and the new name (value). - Output: The renamed DataFrame
df_renamedis printed, showing 'First Name', 'Test Score', and 'Student Age' instead of the original names.
Important Note
- Similar to renaming a single column, the
rename()method returns a new DataFrame. If you want to modify the original DataFrame directly, you can use theinplace=Trueparameter:
df.rename(columns={
'Name': 'First Name',
'Score': 'Test Score',
'Age': 'Student Age'
}, 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!
