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

Python Pandas - แสดงค่าดัชนีซ้ำ ยกเว้นครั้งแรก

ในการระบุค่าดัชนี (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 except the first occurrence...\n", index.duplicated(keep='first'))

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

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 first occurrence...\n", index.duplicated(keep='first'))

ผลลัพธ์

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 first occurrence... [False False False False True]

คำอธิบายผลลัพธ์

ค่า True อยู่ที่ตำแหน่งที่ 4 (Airplane ตัวที่สอง) เนื่องจากเป็นค่าซ้ำที่ไม่ใช่ครั้งแรก ส่วน Airplane ตัวแรก (ตำแหน่งที่ 2) เป็นครั้งแรก จึงเป็น False