The 6 AI Engineering Patterns, come build with Greg live:Β Starts Jan 6th, 2025
Leverage
Pandas functions

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.

pandas.DataFrame.rename(columns={'old_column_name':'new_column_name'})

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.

pandas.DataFrame.rename(columns={"old_column_name" : "new_column_name"})

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

pandas.DataFrame.columns = ['your', 'new', 'column', 'names']

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.

pandas.DataFrame.set_axis(['your', 'new', 'column', 'names'2], axis=1)

In order to grok these methods, let’s look at a couple of examples

Link to code

Official Documentation

On this page