Renaming column names in Pandas
To rename the column names of a Pandas DataFrame, you can use the DataFrame.rename()
method.
Here is an example:
import pandas as pd
# Load a CSV file into a DataFrame
df = pd.read_csv('data.csv')
# Print the original column names
print(df.columns)
# Rename the columns
df = df.rename(columns={'old_name_1': 'new_name_1', 'old_name_2': 'new_name_2'})
# Print the new column names
print(df.columns)
Watch a video course
Python - The Practical Guide
The rename()
method takes a columns
parameter, which is a dictionary that maps the old column names to the new ones. You can specify the names of as many columns as you want in this dictionary.
You can also use the inplace
parameter to specify whether the renaming should be done in-place, without creating a new DataFrame. For example:
df.rename(columns={'old_name': 'new_name'}, inplace=True)
This will rename the column old_name
to new_name
in the same DataFrame, df
, without creating a new one.