Python Pandas - Insert a new index value at a specific position

PythonServer Side ProgrammingProgramming

To insert a new index value at a specific position, use the index.insert() method in Pandas. At first, import the required libraries -

import pandas as pd

Creating the Pandas index −

index = pd.Index(['Car','Bike','Airplane','Ship','Truck'])

Display the index −

print("Pandas Index...
",index)

Insert a new value at a specific position using the insert() method. The first parameter in the insert() is the location where the new index value is placed. The 2 here means the new index value gets inserted at index 2 i.e. position 3. The second parameter is the new index value to be inserted.

print("
After inserting a new index value...
", index.insert(2, 'Suburban'))

Example

Following is the code −

import pandas as pd

# Creating the Pandas index
index = pd.Index(['Car','Bike','Airplane','Ship','Truck'])

# Display the index
print("Pandas Index...
",index) # Return the dtype of the data print("
The dtype object...
",index.dtype) # Insert a new value at a specific position using the insert() method # The first parameter in the insert() is the location where the new index value is placed. # The 2 here means the new index value gets inserted at index 2 i.e. position 3 # The second parameter is the new index value to be inserted. print("
After inserting a new index value...
", index.insert(2, 'Suburban'))

Output

This will produce the following output −

Pandas Index...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck'], dtype='object')

The dtype object...
object

After inserting a new index value...
Index(['Car', 'Bike', 'Suburban', 'Airplane', 'Ship', 'Truck'], dtype='object')
raja
Updated on 13-Oct-2021 07:11:34

Advertisements