Renaming column names in Pandas
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.
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:
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
:
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:
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:
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
:
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:
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:
Was this article helpful?