Index.insert() Method in Pandas

In this tutorial, we are going to learn about the index.insert() method in Python pandas with a set of examples.


Pandas Index.insert() Method

Python is an awesome language for performing data analysis mainly because of the ecosystem of the data-centric Python packages. Python is one of the important packages in Python that lets us import and analyze data at a very feasible level. 

Pandas has a function known as index.insert()  that helps us to make a new index by inserting an item at a certain location. The syntax for inserting indexed  items in python is: 

Syntax

index.insert(loc, item)





Example 1:

# importing pandas as pd
import pandas as pd

# Creating the Index
my_index = pd.Index(['green', 'red', 'blue',

                    'yellow', 'brown'])

# Print the Index
My_index

Output

Index(['green', 'red', 'blue', 'yellow', 'brown'], dtype='object')

Let’s insert ‘black’ as the 1st index now:

my_index.insert(1, 'black')

Output

Index(['green', 'black', 'red', 'blue', 'yellow', 'brown'], dtype='object')

we can insert negative indexing as well using the index.insert() method at the second position from the last in the index.

Example 2

# importing pandas as pd
import pandas as pd

# Creating the Index
my_index = pd.Index(['green', 'red', 'blue',

                    'yellow', 'brown'])

# Print the Index
My_index

Output

Index(['green', 'red', 'blue', 'yellow', 'brown'], dtype='object')

As the output suggests, the values have been inserted at the described location.