Rename Columns using Python

When working on a data science task, sometimes the dataset you are using has features with very complex names, so to keep things simple we can rename the columns with complex names. So in this article, I will walk you through a tutorial on how to rename columns using Python.

Rename Columns using Python

We generally use the pandas library in Python while working on a dataset. The pandas library itself provides a function to rename columns known as pandas.DataFrame.rename. But we can also use Python’s assigning operator while renaming a column. So below is how you can rename columns by using the rename method by the Pandas library in Python:

import pandas as pd
data = pd.read_csv('https://raw.githubusercontent.com/amankharwal/Website-data/master/Advertising.csv')
print(data.head())
   Unnamed: 0     TV  Radio  Newspaper  Sales
0           1  230.1   37.8       69.2   22.1
1           2   44.5   39.3       45.1   10.4
2           3   17.2   45.9       69.3    9.3
3           4  151.5   41.3       58.5   18.5
4           5  180.8   10.8       58.4   12.9
data = data.rename(columns={"TV": "Television", "Sales": "Total Sales"})
print(data.head())
   Unnamed: 0  Television  Radio  Newspaper  Total Sales
0           1       230.1   37.8       69.2         22.1
1           2        44.5   39.3       45.1         10.4
2           3        17.2   45.9       69.3          9.3
3           4       151.5   41.3       58.5         18.5
4           5       180.8   10.8       58.4         12.9

Now below is how you can rename columns without using any method of the pandas library:

data.columns = ["Unnamed","TV", "Radio", "NS", "TS"]
print(data.head())
   Unnamed     TV  Radio    NS    TS
0        1  230.1   37.8  69.2  22.1
1        2   44.5   39.3  45.1  10.4
2        3   17.2   45.9  69.3   9.3
3        4  151.5   41.3  58.5  18.5
4        5  180.8   10.8  58.4  12.9

Here we are just assigning the new column names to the old names.

Also, Read – Python Projects with Source Code.

Summary

So this is how you can rename any column by using the pandas.DataFrame.rename method. We can also assign the new column names by using the assigning operator in Python. I hope you liked this article on how to rename a column using Pandas library in Python. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1435

Leave a Reply