Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Thay đổi tên Index


Để thay đổi tên Index, hãy sử dụng phương thức index.rename() trong Pandas. Trước tiên, nhập các thư viện cần thiết:

import pandas as pd

Tạo Pandas Index:

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

Hiển thị Pandas Index:

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

Đổi tên index:

print("\nĐổi tên index...\n", index.rename('Mode_of_Transport'))

Ví dụ

Dưới đây là mã hoàn chỉnh:

import pandas as pd
# Tạo Pandas Index
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name='Transport')
# Hiển thị Pandas Index
print("Pandas Index...\n", index)
# Trả về số lượng phần tử trong Index
print("\nSố lượng phần tử trong index...\n", index.size)
# Trả về kiểu dữ liệu
print("\nĐối tượng dtype...\n", index.dtype)
# Đổi tên index
print("\nĐổi tên index...\n", index.rename('Mode_of_Transport'))

Kết quả

Đoạn mã trên sẽ cho ra kết quả sau:

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')