ในการระบุค่าดัชนี (Index) ที่ซ้ำกัน แต่ไม่นับครั้งสุดท้าย ให้ใช้เมธอด index.duplicated() พร้อมตั้งค่าพารามิเตอร์ 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("\nIndicating duplicate values except the last occurrence...\n", index.duplicated(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 dimensions...\n", index.ndim)
# ระบุค่าซ้ำ ยกเว้นครั้งสุดท้าย
print("\nIndicating duplicate values except the last occurrence...\n", index.duplicated(keep='last'))
ผลลัพธ์
Pandas Index with duplicates... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object')
The dtype object... object
Get the dimensions... 1
Indicating duplicate values except the last occurrence... [False False True False False]
คำอธิบายผลลัพธ์
ค่า True อยู่ที่ตำแหน่งที่ 2 (Airplane ตัวแรก) เนื่องจากเป็นค่าซ้ำที่ไม่ใช่ครั้งสุดท้าย ส่วน Airplane ตัวที่สอง (ตำแหน่งที่ 4) เป็นครั้งสุดท้าย จึงเป็น False