How to rename multiple columns at once?

0273

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

  1. Creating the DataFrame: We create a DataFrame df with columns 'Name', 'Score', and 'Age'.
  2. Renaming Columns: The rename() method is called with a dictionary in the columns parameter. Each key-value pair in the dictionary represents the current column name (key) and the new name (value).
  3. Output: The renamed DataFrame df_renamed is 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 the inplace=True parameter:
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!

0 Comments

no data
Be the first to share your comment!