• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Rename Column by Index in Dataframes

Rename Column by Index in Dataframes

Author: Aditya Raj
Last Updated: September 21, 2022

Dataframes are used to handle tabular data in python. In this article, we will discuss how we can rename a column by index in dataframes in python.

Change Column Name Using Index Number

We can access the column names in a dataframe using the ‘columns’ attribute. The columns attribute of a dataframe contains an Index object. The Index object contains a list of column names as you can see in the following example.

import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)

Output:

The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')

You can access the array of column names using the ‘values’ attribute of the Index object as follows.

import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)

Output:

The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']

To rename the column by index in the dataframe, we can modify the array in the values attribute. For instance, you can change the name of the first column using index 0 of the values array as follows.

import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)
df.columns.values[0]="First Name"
print("The modified column object is:")
print(df.columns)
print("The modified columns are:")
print(df.columns.values)

Output:

The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']
The modified column object is:
Index(['First Name', 'Roll', 'Language'], dtype='object')
The modified columns are:
['First Name' 'Roll' 'Language']

In this approach, we cannot change multiple column names at once. To change multiple column names, you need to rename each column name one by one as follows.

import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)
df.columns.values[0]="First Name"
df.columns.values[1]="Roll Number"
print("The modified column object is:")
print(df.columns)
print("The modified columns are:")
print(df.columns.values)

Output:

The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']
The modified column object is:
Index(['First Name', 'Roll Number', 'Language'], dtype='object')
The modified columns are:
['First Name' 'Roll Number' 'Language']

We can also change multiple column names by index at once using the rename() method. Let us discuss this approach. 

Suggested Reading: If you are into machine learning, you can read this article on regression in machine learning. You might also like this article on k-means clustering with numerical example.

Change Column Name Using rename() Method in a DataFrame

We can use the rename() method to rename multiple columns using the index numbers. The rename() method, when invoked on a dataframe, takes a dictionary as its input argument. The dictionary should contain the column names that need to be renamed as the keys. The new column names should be the values associated with the original keys. After execution, the rename() method returns a new dataframe with the modified column names. 

To modify the column names using the index number and rename() method, we will first obtain the array of column names using the columns.values attribute of the dataframe. After that, we will create a dictionary with column names as keys and the new column names as associated values for the keys. Then, we will pass the dictionary to the rename() method. After execution, the rename() method will return the dataframe with modified column names as follows.

import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)
nameDict={"Name":"First Name","Roll":"Roll No."}
df=df.rename(columns=nameDict)
print("The modified column object is:")
print(df.columns)
print("The modified columns are:")
print(df.columns.values)

Output:

The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']
The modified column object is:
Index(['First Name', 'Roll No.', 'Language'], dtype='object')
The modified columns are:
['First Name' 'Roll No.' 'Language']

Conclusion

In this article, we have discussed how to rename column by index in dataframes in python. To know more about python programming, you can read this article on dictionary comprehension in python. You might also like this article on list comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us