How to rename columns?

0117

Renaming columns in a Pandas DataFrame can be done easily using the rename() method. This method allows you to specify which columns to rename and what their new names should be.

Example of Renaming 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 columns
df_renamed = df.rename(columns={'Name': 'First Name', 'Score': 'Test Score'})

# Display the renamed DataFrame
print("\nRenamed DataFrame:")
print(df_renamed)

Explanation

  1. Creating the DataFrame: We first create a DataFrame df with columns 'Name', 'Score', and 'Age'.
  2. Renaming Columns: The rename() method is called on the DataFrame, passing a dictionary to the columns parameter. The keys of the dictionary are the current column names, and the values are the new names you want to assign.
  3. Output: The renamed DataFrame df_renamed is printed, showing 'First Name' and 'Test Score' instead of 'Name' and 'Score'.

Important Note

  • The rename() method returns a new DataFrame with the updated column names. If you want to modify the original DataFrame in place, you can use the inplace=True parameter:
df.rename(columns={'Name': 'First Name', 'Score': 'Test Score'}, inplace=True)

Further Learning

To learn more about DataFrame operations, you might find these resources helpful:

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

0 Comments

no data
Be the first to share your comment!