Renaming column names in Pandas

To rename the column names of a Pandas DataFrame, you can use the ‘DataFrame.rename()‘ method. This method takes a dictionary of old column names as keys and new column names as values, and it returns a new DataFrame with the updated column names.

Here’s an example of how you can use ‘rename()‘ to rename the columns of a DataFrame:

import pandas as pd

# Load a sample DataFrame
df = pd.read_csv("data.csv")

# Rename the columns
df = df.rename(columns={'old_col_1': 'new_col_1', 'old_col_2': 'new_col_2'})

# Print the DataFrame with the updated column names
print(df)

You can also use the ‘inplace‘ parameter to update the column names in place, without creating a new DataFrame:

import pandas as pd

# Load a sample DataFrame
df = pd.read_csv("data.csv")

# Rename the columns in place
df.rename(columns={'old_col_1': 'new_col_1', 'old_col_2': 'new_col_2'}, inplace=True)

# Print the DataFrame with the updated column names
print(df)

Keep in mind that the ‘rename()‘ method works with the column labels, not the column names. If you want to change the actual names of the columns in the DataFrame, you can use the ‘columns‘ attribute:

import pandas as pd

# Load a sample DataFrame
df = pd.read_csv("data.csv")

# Update the column names
df.columns = ['new_col_1', 'new_col_2']

# Print the DataFrame with the updated column names
print(df)

Related: Delete a column from a Pandas DataFrame

Leave a Comment