How to Rename Columns in a Pandas DataFrame

Suppose we’re dealing with a DataFrame df with columns A, B, and C.

Rename specific columns

We can rename specific columns using rename(). Note that we can rename any number of columns.

In this example, we want to lowercase the first two columns.

df = df.rename(columns={'A':'a', 'B':'b'})
df = df.rename({'A':'a', 'B':'b'}, axis=1) # Same output

We can also rename in place if we don’t want to make a copy.

df.rename(columns={'A':'a', 'B':'b'}, inplace=True)

Errors with non-existent columns

We can specify an errors parameter if we want to raise errors when a column doesn’t exist.

df.rename(columns={'D':'d'}, errors='raise')

If raise, raise a KeyError when a dict-like mapper, index, or columns contains labels that are not present in the Index being transformed. If ignore, existing keys will be renamed and extra keys will be ignored.