Python | Pandas Index.insert()
Last Updated :
17 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.insert()
function make new Index inserting new item at location. This function also follows Python list.append()
semantics for negative values. If the negative value are passed then it start from the other end.
Syntax: Index.insert(loc, item)
Parameters :
loc : int
item : object
Returns : new_index : Index
Example #1: Use Index.insert()
function to insert a new value in the Index.
import pandas as pd
idx = pd.Index([ 'Labrador' , 'Beagle' , 'Labrador' ,
'Lhasa' , 'Husky' , 'Beagle' ])
idx
|
Output :
Now insert ‘Great_Dane’ at the 1st index.
idx.insert( 1 , 'Great_Dane' )
|
Output :
As we can see in the output, the Index.insert()
function has inserted the passed value at the desired location.
Example #2: Use Index.insert()
function to insert a value into the Index at the second position from the last in the Index.
import pandas as pd
idx = pd.Index([ 'Labrador' , 'Beagle' , 'Labrador' ,
'Lhasa' , 'Husky' , 'Beagle' ])
idx
|
Output :
Now insert ‘Great_Dane’ at the 1st index from the last.
idx.insert( - 1 , 'Great_Dane' )
|
Output :
As we can see in the output, the passed value has been inserted into the Index at the desired location.
Share your thoughts in the comments
Please Login to comment...