ในการลบค่าดัชนี (Index) ที่ซ้ำกันทั้งหมด ให้ใช้เมธอด index.drop_duplicates() พร้อมตั้งค่าพารามิเตอร์ keep=False
ขั้นตอนการทำงาน
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 (drops all occurrences)...\n", index.drop_duplicates(keep=False))
ตัวอย่างโค้ดสมบูรณ์
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)
# ลบค่าซ้ำทั้งหมด (keep=False)
print("\nIndex with duplicate values removed (drops all occurrences)...\n", index.drop_duplicates(keep=False))
ผลลัพธ์
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 (drops all occurrences)... Index(['Car', 'Bike', 'Ship'], dtype='object')
คำอธิบาย
เมื่อตั้งค่า keep=False ค่าที่ซ้ำกัน ทุกครั้ง จะถูกลบออกไป ดังนั้น 'Airplane' ที่ซ้ำกัน 2 ครั้ง จะหายไปทั้งคู่ เหลือเฉพาะค่าที่ไม่ซ้ำกันคือ 'Car', 'Bike', 'Ship'