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

Python Pandas - สร้างดัชนีใหม่โดยลบชื่อป้ายกำกับที่ระบุ

ในการสร้างดัชนี (Index) ใหม่โดยลบชื่อป้ายกำกับ (labels) ที่ระบุ ให้ใช้เมธอด index.drop() และส่งรายการชื่อป้ายกำกับที่ต้องการลบเข้าไป

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

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

import pandas as pd

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

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

3. แสดงดัชนี

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

4. ลบชื่อป้ายกำกับที่ระบุ

print("\nUpdated index after deleting labels...\n", index.drop(['Bike', 'Ship']))

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

import pandas as pd

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

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

# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)

# แสดงรูปร่างของข้อมูล
print("\nA tuple of the shape of underlying data...\n", index.shape)

# ลบชื่อป้ายกำกับ 'Bike' และ 'Ship'
print("\nUpdated index after deleting labels...\n", index.drop(['Bike', 'Ship']))

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')
The dtype object... object
A tuple of the shape of underlying data... (5,)
Updated index after deleting labels... Index(['Car', 'Truck', 'Airplane'], dtype='object')

คำอธิบาย

เมธอด drop() จะสร้างดัชนีใหม่โดยไม่มีชื่อป้ายกำกับที่ระบุ ('Bike' และ 'Ship') ดัชนีเดิมจะไม่เปลี่ยนแปลง