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

Python Pandas - ตั้งชื่อดัชนีที่สร้างไว้แล้ว (index.set_names)

ในการตั้งชื่อให้ดัชนี (Index) ที่สร้างไว้แล้ว ให้ใช้เมธอด index.set_names() ใน Pandas

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

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

import pandas as pd

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

index = pd.Index(["Electronics", "Mobile Phones", "Accessories", "Home Decor", "Books"])

3. แสดงดัชนี

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

4. ตั้งชื่อดัชนี

print("\nSet the index name...\n", index.set_names('Products'))

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

import pandas as pd

# สร้างดัชนี
index = pd.Index(["Electronics", "Mobile Phones", "Accessories", "Home Decor", "Books"])

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

# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)

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

# ตั้งชื่อดัชนี
print("\nSet the index name...\n", index.set_names('Products'))

ผลลัพธ์

Pandas Index... Index(['Electronics', 'Mobile Phones', 'Accessories', 'Home Decor', 'Books'], dtype='object')
Number of elements in the index... 5
The dtype object... object
Set the index name... Index(['Electronics', 'Mobile Phones', 'Accessories', 'Home Decor', 'Books'], dtype='object', name='Products')

คำอธิบาย

set_names() คืนค่าดัชนีใหม่ที่มีชื่อตามที่ระบุ ดัชนีเดิมไม่เปลี่ยนแปลง หากต้องการเปลี่ยนจริง ให้กำหนด: index = index.set_names('Products')