- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Insert a new index value at a specific position
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...\n",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("\nAfter inserting a new index value...\n", 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...\n",index) # Return the dtype of the data print("\nThe dtype object...\n",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("\nAfter inserting a new index value...\n", 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')
Advertisements