Explain Codes LogoExplain Codes Logo

Renaming column names in Pandas

python
pandas
dataframe
method-chaining
Alex KataevbyAlex Kataev·Mar 4, 2025
TLDR

The fastest way to rename columns in a Pandas DataFrame is to use the rename() method which employs a dictionary: old names as keys and new names as values.

df_renamed = df.rename(columns={'OldName1': 'NewName1', 'OldName2': 'NewName2'})

Result: DataFrame with updated column names, OldName1 becomes NewName1, and so on.

Want to avoid making an extra copy? Use the inplace parameter to modify the original DataFrame:

df.rename(columns={'OldName1': 'NewName1', 'OldName2': 'NewName2'}, inplace=True) # It's like a DIY, instant modifications!

Going all-in: Changing all column names

Sometimes you need to change all column names at once. This can be done directly using df.columns:

df.columns = ['NewName1', 'NewName2', 'NewName3'] # For times when you just got tired of old names.

Something's not right: Dealing with errors

If you're dealing with large datasets, it's possible to make mistakes. For instance, trying to rename a column that doesn't exist would normally raise an error. But Python's got your back. Use the errors parameter:

df.rename(columns={'NonexistentOldName': 'NewName'}, errors='ignore') # Ignore the typos, everybody makes one!

Result: If 'NonexistentOldName' doesn't exist, this function just moves on without an error—it's like that typo never happened.

Don't like surprises? Use errors='raise' instead to shoot an error whenever there's a mismatch:

df.rename(columns={'NonexistentOldName': 'NewName'}, errors='raise') # Let's catch those mistakes red-handed!

Partial renaming: Changing the names you don't like

Sometimes you might want to rename only a few columns. You can do this by specifying only those columns in the dictionary passed to rename:

df.rename(columns={'OldName2': 'NewName2'}, inplace=True) # Only 'OldName2' gets a new name, while others keep their identity.

Result: DataFrame with only 'OldName2' changed to 'NewName2'. All other column names remain the same.

Keeping it clean: Removing unwanted characters from column names

In case your column names have unwanted characters like '$', you can remove these using string manipulation:

df.columns = df.columns.str.replace('$', '') # Like getting rid of that pesky gum, stuck to your shoe.

Method chaining: One after another

At times, you might want to perform several operations in one line. Python calls it method chaining. Here's an example:

# Step 1: Rename 'OldName1' to 'NewName1'. # Step 2: Set 'FinalName1' & 'FinalName2' as column names. # Why? Because sometimes we like to keep things short and sweet. df_renamed = df.rename(columns={'OldName1': 'NewName1'}).set_axis(['FinalName1', 'FinalName2'], axis=1)