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