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

Python Pandas - เปลี่ยนชื่อ Index

การเปลี่ยนชื่อ Index ใน Pandas

ใช้เมธอด index.rename() เพื่อเปลี่ยนชื่อของ Index โดยไม่เปลี่ยนแปลงข้อมูลภายใน

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Index พร้อมชื่อเดิม
  3. แสดง Index เดิม
  4. ใช้ rename() กำหนดชื่อใหม่

ตัวอย่างโค้ด

import pandas as pd

# สร้าง Index ชื่อ 'Transport'
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], name='Transport')

# แสดง Index เดิม
print("Pandas Index...\n", index)

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

# เปลี่ยนชื่อ Index เป็น 'Mode_of_Transport'
print("\nRename the index...\n", index.rename('Mode_of_Transport'))

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport')
Number of elements in the index... 6
The dtype object... object
Rename the index... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Mode_of_Transport')

คำอธิบาย

เมธอด rename() คืนค่า Index ใหม่ที่มีชื่อตามที่ระบุ ข้อมูลและลำดับขององค์ประกอบยังคงเดิม