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

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


หากต้องการเปลี่ยนชื่อดัชนี ให้ใช้ index.rename() วิธีการในแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import pandas as pd

การสร้างดัชนีนุ่น -

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

แสดงดัชนีหมีแพนด้า −

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

เปลี่ยนชื่อดัชนี −

print("\nRename the index...\n",index.rename('Mode_of_Transport'))

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

import pandas as pd

# Creating Pandas index
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Rename the index
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')