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

Python Pandas - แทรกค่า Index ใหม่ที่ตำแหน่งเฉพาะเจาะจง

การแทรกค่า Index ใหม่ที่ตำแหน่งที่กำหนด

ใช้เมธอด index.insert() โดยระบุตำแหน่ง (index) ที่ต้องการแทรก

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Index
  3. แสดง Index
  4. ใช้ insert(ตำแหน่ง, 'ค่าใหม่')

ตัวอย่างโค้ด

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' ที่ตำแหน่ง 2 (ก่อน Airplane)
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')

คำอธิบาย

ตำแหน่ง 2 หมายถึง index ลำดับที่ 2 (เริ่มจาก 0) ดังนั้น 'Suburban' จะถูกแทรกก่อน 'Airplane' (ซึ่งอยู่ที่ index 2 เดิม)