Renaming column names in Pandas
To rename the column names of a Pandas DataFrame, you can use the DataFrame.rename() method.
To rename the column names of a Pandas DataFrame, you can use the DataFrame.rename() method.
Here is an example:
Rename the column names of a Pandas DataFrame
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)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
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:
Rename the column names of a Pandas DataFrame, using the inplace parameter to specify whether the renaming should be done in-place
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.