To rename a single column in a Pandas DataFrame, you can use the rename() method and specify the current column name along with the new name in a dictionary. This allows you to change just one column without affecting the others.
Example of Renaming a Single Column
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 a single column
df_renamed = df.rename(columns={'Name': 'First Name'})
# 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 the Column: The
rename()method is called with a dictionary in thecolumnsparameter. The key is the current column name ('Name'), and the value is the new name ('First Name'). - Output: The renamed DataFrame
df_renamedis printed, showing 'First Name' instead of 'Name'.
Important Note
- The
rename()method returns a new DataFrame with the updated column name. If you want to modify the original DataFrame in place, you can use theinplace=Trueparameter:
df.rename(columns={'Name': 'First Name'}, inplace=True)
Further Learning
For more details on renaming columns and other DataFrame operations, you can check:
If you have any more questions or need further examples, feel free to ask!
