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
- Creating the DataFrame: We first create a DataFrame
dfwith columns 'Name', 'Score', and 'Age'. - Renaming Columns: The
rename()method is called on the DataFrame, passing a dictionary to thecolumnsparameter. The keys of the dictionary are the current column names, and the values are the new names you want to assign. - Output: The renamed DataFrame
df_renamedis 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 theinplace=Trueparameter:
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!
