Pandas Change Column Names β 3 Methods
Change column names in pandas
Pandas Change Column names β Changing column names within pandas is easy. You only need to decide which method you want to use. Depending on your use case, you can pick the best one for you.
The easiest and most popular one will be done via the .rename() method. But look below for 2 other ways.
I use this function when I want to clean up my column names. Itβs good to practice table hygiene and keep your column names short and readable.
Pseudo Code: Rename your old column name to your new column name.
Pandas Change Column Names
Method 1 β Pandas Rename
The first method that we suggest is using Pandas Rename. Rename takes a dict with a key of your old column name and a key of your new column name. Amazingly, it also takes a function!
This means that youβre able to apply a string function to your column names and apply a transformation to all of your column names. For instance if you wanted to upper case your column names.
Method 2 β Pandas .columns attribute
The second way to rename your columns is by setting DataFrame.columns to the list of your new column names. This will completely overwrite your original columns with your new list.
Watch out though β Pandas does not know which columns youβre trying to rename. If you mistakenly mis-order your new column names you will have column names that donβt match the column contents. See below for an example
Method 3 β Pandas .set_axis(axis=1)
The last method (and our least favorite) is to set_axis on top of your DataFrame and specify axis=1. This will have similar functionality as setting .columns. In this case, Pandas will completely overwrite all of your column names with whatever you give it.
In order to grok these methods, letβs look at a couple of examples