To rename column names in Pandas, you can use the rename method on a Pandas DataFrame object. The rename method takes a dictionary that maps old column names to new column names.
Here's an example:
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35],
'Gender': ['Male', 'Female', 'Male']
})
# Rename the 'Gender' column to 'Sex'
df = df.rename(columns={'Gender': 'Sex'})
# Print the DataFrame to verify the column name change
print(df)
Output:
markdown
Name Age Sex
0 John 25 Male
1 Alice 30 Female
2 Bob 35 Male
markdown
Name Age Sex
0 John 25 Male
1 Alice 30 Female
2 Bob 35 Male
In the example above, we first created a DataFrame with columns named 'Name', 'Age', and 'Gender'. Then we used the rename method to change the name of the 'Gender' column to 'Sex', and assigned the result back to the original DataFrame. Finally, we printed the DataFrame to verify that the column name change was successful.
Comments (0)