Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - แทรกค่า Index ใหม่ที่ตำแหน่งแรกจากท้าย

การแทรกค่า Index ใหม่ที่ตำแหน่ง -1 (ตัวแรกจากท้าย)

ใช้เมธอด index.insert() โดยระบุตำแหน่ง -1 เพื่อแทรกค่าใหม่ก่อนองค์ประกอบสุดท้าย

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Index
  3. แสดง Index
  4. ใช้ 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 เดิม