How to Rename Columns in Pandas (With Examples)


Often you may want to rename one or more columns in a pandas DataFrame. Fortunately this is easy to do using the pandas rename() function, which uses the following syntax:

df.rename(columns={'old_col':'new_col', 'old_col2':'new_col2'}, inplace=True)

This tutorial shows several examples of how to use this function in practice on the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'rating': [90, 85, 82, 88, 94, 90, 76, 75, 87, 86],
                   'points': [25, 20, 14, 16, 27, 20, 12, 15, 14, 19],
                   'assists': [5, 7, 7, 8, 5, 7, 6, 9, 9, 5],
                   'rebounds': [11, 8, 10, 6, 6, 9, 6, 10, 10, 7]})          

#view DataFrame 
print(df)

   rating  points  assists  rebounds
0      90      25        5        11
1      85      20        7         8
2      82      14        7        10
3      88      16        8         6
4      94      27        5         6
5      90      20        7         9
6      76      12        6         6
7      75      15        9        10
8      87      14        9        10
9      86      19        5         7

Example 1: Rename a Single Column

The following code shows how to rename a single column in the DataFrame:

#rename 'rating' to 'overall'
df.rename(columns={'rating': 'overall'}, inplace=True)      

#view DataFrame 
print(df)

        overall	points	assists	rebounds
0	90	25	5	11
1	85	20	7	8
2	82	14	7	10
3	88	16	8	6
4	94	27	5	6
5	90	20	7	9
6	76	12	6	6
7	75	15	9	10
8	87	14	9	10
9	86	19	5	7

Example 2: Rename Multiple Columns

The following code shows how to rename multiple columns in the DataFrame:

#rename 'rating' and 'rebounds' columns
df.rename(columns={'rating': 'overall', 'rebounds':'rebs'}, inplace=True)      

#view DataFrame 
print(df)

        overall	points	assists	rebs
0	90	25	5	11
1	85	20	7	8
2	82	14	7	10
3	88	16	8	6
4	94	27	5	6
5	90	20	7	9
6	76	12	6	6
7	75	15	9	10
8	87	14	9	10
9	86	19	5	7

Example 3: Rename All Columns

The following code shows how to rename all columns in the DataFrame:

#rename all columns
df.columns = ['overall', 'pts', 'ast', 'rebs']

#view DataFrame 
print(df)

        overall	 pts	ast	rebs
0	90	 25	5	11
1	85	 20	7	8
2	82	 14	7	10
3	88	 16	8	6
4	94	 27	5	6
5	90	 20	7	9
6	76	 12	6	6
7	75	 15	9	10
8	87	 14	9	10
9	86	 19	5	7

Additional Resources

How to Insert a Column Into a Pandas DataFrame
How to Add an Empty Column to a Pandas DataFrame
How to Create a New Column Based on a Condition in Pandas

Leave a Reply

Your email address will not be published. Required fields are marked *