ในการลบค่าดัชนี (Index) ที่ซ้ำกัน แต่คงไว้ครั้งสุดท้าย ให้ใช้เมธอด index.drop_duplicates() พร้อมตั้งค่าพารามิเตอร์ keep='last'
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนีที่มีค่าซ้ำ
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'])
3. แสดงดัชนี
print("Pandas Index with duplicates...\n", index)
4. ลบค่าซ้ำ คงไว้ครั้งสุดท้าย
print("\nIndex with duplicate values removed (keeping the last occurrence)...\n", index.drop_duplicates(keep='last'))
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้างดัชนีที่มีค่าซ้ำ
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'])
# แสดงดัชนี
print("Pandas Index with duplicates...\n", index)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# แสดงไบต์ของข้อมูล
print("\nGet the bytes...\n", index.nbytes)
# แสดงมิติของข้อมูล
print("\nGet the dimensions...\n", index.ndim)
# ลบค่าซ้ำ คงไว้ครั้งสุดท้าย
print("\nIndex with duplicate values removed (keeping the last occurrence)...\n", index.drop_duplicates(keep='last'))
ผลลัพธ์
Pandas Index with duplicates... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object')
The dtype object... object
Get the bytes... 40
Get the dimensions... 1
Index with duplicate values removed (keeping the last occurrence)... Index(['Car', 'Bike', 'Ship', 'Airplane'], dtype='object')
คำอธิบาย
เมื่อตั้งค่า keep='last' จะคงค่าที่ซ้ำกันไว้เฉพาะ ครั้งสุดท้าย ดังนั้น 'Airplane' ตัวแรก (ตำแหน่งที่ 2) ถูกลบออก เหลือ 'Airplane' ตัวที่สอง (ตำแหน่งที่ 4) คล้ายกับ 'Car', 'Bike', 'Ship' ที่ไม่ซ้ำกัน จึงคงอยู่