To insert a new index value at the first index from the last, use the index.insert() method. Set the last index value -1 and the value to be inserted as parameters.
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...\n",index)Insert a new value at the first index from the last using the insert() method. The first parameter in the insert() is the location where the new index value is placed. The -1 here means the new index value gets inserted at the first index from the last. The second parameter is the new index value to be inserted.
index.insert(-1, '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...\n",index)
# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)
# Insert a new value at the first index from the last using the insert() method.
# The first parameter in the insert() is the location where the new index value is placed.
# The -1 here means the new index value gets inserted at the first index from the last.
# The second parameter is the new index value to be inserted.
print("\nAfter inserting a new index value...\n", index.insert(-1, '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', 'Airplane', 'Ship', 'Suburban', 'Truck'], dtype='object')