ในการแทรกค่าดัชนีใหม่ในตำแหน่งเฉพาะ ให้ใช้ index.insert() วิธีการในแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
การสร้างดัชนีนุ่น -
index = pd.Index(['Car','Bike','Airplane','Ship','Truck'])
แสดงดัชนี -
print("Pandas Index...\n",index) แทรกค่าใหม่ที่ตำแหน่งเฉพาะโดยใช้เมธอด insert() พารามิเตอร์แรกใน insert() คือตำแหน่งที่วางค่าดัชนีใหม่ 2 ในที่นี้หมายความว่ามีการแทรกค่าดัชนีใหม่ที่ดัชนี 2 เช่น ตำแหน่ง 3 พารามิเตอร์ที่สองคือค่าดัชนีใหม่ที่จะแทรก
print("\nAfter inserting a new index value...\n", index.insert(2, 'Suburban'))
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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')) ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
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')