Rename Columns

January 28, 2018

Rename Columns

It is quite common to have datasets where the columns provided are not the most intuitively named - pandas provides us with multiple ways to rename them.


Import Libraries

import pandas as pd
import seaborn as sns


Load Data

tips = sns.load_dataset('tips')
tips.head()
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4


We can access the columns using the columns variable.

print(tips.columns)
Index(['total_bill', 'tip', 'sex', 'smoker', 'day', 'time', 'size'], dtype='object')


We can replace the existing columns by assigning a list of the same length as the existing column to the DataFrame’s columns variable.

new_columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
tips.columns = new_columns
tips.head()
a b c d e f g
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4


If you are looking for a more targeted operation, you are covered by the rename method.

tips = tips.rename(columns={'a': 'total_bill_amount'})
tips.head(5)
total_bill_amount b c d e f g
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4


We can also pass a function to rename and specify the axis for it to be applied.

tips = tips.rename(str.upper, axis=1)
tips.head(2)
TOTAL_BILL_AMOUNT B C D E F G
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
comments powered by Disqus