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

Python Pandas - ลบค่าดัชนีซ้ำ คงไว้ครั้งแรก (keep='first')

ในการลบค่าดัชนี (Index) ที่ซ้ำกัน แต่คงไว้ครั้งแรก ให้ใช้เมธอด index.drop_duplicates() พร้อมตั้งค่าพารามิเตอร์ 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. ลบค่าซ้ำ คงไว้ครั้งแรก

index.drop_duplicates(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 bytes...\n", index.nbytes)

# แสดงมิติของข้อมูล
print("\nGet the dimensions...\n", index.ndim)

# ลบค่าซ้ำ คงไว้ครั้งแรก
print("\nIndex with duplicate values removed (keeping the first occurrence)...\n", index.drop_duplicates(keep='first'))

ผลลัพธ์

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 (keeping the first occurrence)... Index(['Car', 'Bike', 'Airplane', 'Ship'], dtype='object')

คำอธิบาย

เมื่อตั้งค่า keep='first' (ค่าเริ่มต้น) จะคงค่าที่ซ้ำกันไว้เฉพาะ ครั้งแรก ดังนั้น 'Airplane' ตัวที่สอง (ตำแหน่งที่ 4) ถูกลบออก เหลือ 'Airplane' ตัวแรก (ตำแหน่งที่ 2)