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

Python Pandas - ลบค่าดัชนีซ้ำ (ค่าเริ่มต้น keep='first')

ในการลบค่าดัชนี (Index) ที่ซ้ำกัน โดยใช้ค่าเริ่มต้น ให้ใช้เมธอด index.drop_duplicates() โดยไม่ระบุพารามิเตอร์ keep (ค่าเริ่มต้นคือ 'first')

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

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

import pandas as pd

2. สร้างดัชนีที่มีค่าซ้ำ

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

3. แสดงดัชนี

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

4. ลบค่าซ้ำ (ค่าเริ่มต้น)

print("\nIndex with duplicate values removed...\n", index.drop_duplicates())

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

import pandas as pd

# สร้างดัชนีที่มีค่าซ้ำ
index = pd.Index(['Car', 'Bike', 'Truck', 'Car', '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)

# ลบค่าซ้ำ (ค่าเริ่มต้น keep='first')
print("\nIndex with duplicate values removed...\n", index.drop_duplicates())

ผลลัพธ์

Pandas Index with duplicates... Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')
The dtype object... object
Get the bytes... 40
Get the dimensions... 1
Index with duplicate values removed... Index(['Car', 'Bike', 'Truck', 'Airplane'], dtype='object')

คำอธิบาย

ค่าเริ่มต้นของ drop_duplicates() คือ keep='first' ดังนั้น 'Car' ตัวแรกจะถูกเก็บไว้ ส่วน 'Car' ตัวที่สอง (ตำแหน่งที่ 3) จะถูกลบออก