Python | Pandas Index.insert()
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 : objectReturns : new_index : Index
Example #1: Use Index.insert() function to insert a new value in the Index.
# importing pandas as pd import pandas as pd # Creating the Index idx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Index idx |
Output :

Now insert ‘Great_Dane’ at the 1st index.
# Inserting a value at the first position in the 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.
# importing pandas as pd import pandas as pd # Creating the Index idx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Index idx |
Output :

Now insert ‘Great_Dane’ at the 1st index from the last.
# Inserting a value at the first position in the index. 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.
Recommended Posts:
- Python | pandas.map()
- Python | Pandas Panel.mod()
- Python | Pandas Series.take()
- Python | Pandas DataFrame.ix[ ]
- Python | Pandas Series.sem()
- Python | Pandas TimedeltaIndex.max
- Python | Pandas DatetimeIndex.second
- Python | Pandas DatetimeIndex.day
- Python | Pandas Series.str.pad()
- Python | Pandas Series.std()
- Python | Pandas TimedeltaIndex.contains
- Python | Pandas TimedeltaIndex.min
- Python | Pandas Period.day
- Python | Pandas PeriodIndex.second
- Python | Pandas Series.mean()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



