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