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

Python Pandas - ตรวจสอบว่าดัชนีมีค่าซ้ำหรือไม่ (index.has_duplicates)

ในการตรวจสอบว่าดัชนี (Index) มีค่าซ้ำกันหรือไม่ ให้ใช้คุณสมบัติ index.has_duplicates ใน Pandas

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้างดัชนี

index = pd.Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'])

3. แสดงดัชนี

print("Pandas Index...\n", index)

4. ตรวจสอบว่ามีค่าซ้ำหรือไม่

print("\nIs the Pandas index having duplicate values?\n", index.has_duplicates)

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# สร้างดัชนี
index = pd.Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'])

# แสดงดัชนี
print("Pandas Index...\n", index)

# แสดงอาร์เรย์ของข้อมูล
print("\nArray...\n", index.values)

# ตรวจสอบว่ามีค่าซ้ำหรือไม่
print("\nIs the Pandas index having duplicate values?\n", index.has_duplicates)

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')
Array... ['Car' 'Bike' 'Truck' 'Car' 'Airplane']
Is the Pandas index having duplicate values? True

คำอธิบาย

index.has_duplicates คืนค่า True หากดัชนีมีค่าซ้ำกันอย่างน้อยหนึ่งค่า มิฉะนั้นคืนค่า False ในที่นี้ 'Car' ปรากฏ 2 ครั้ง จึงคืนค่า True