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

Python Pandas - Tạo DataFrame giữ nguyên Index và tên gốc

Để tạo DataFrame giữ nguyên cả Index và tên của Index gốc, hãy sử dụng phương thức index.to_frame() không tham số (mặc định index=True).

Các bước thực hiện

1. Import thư viện cần thiết

import pandas as pd

2. Tạo Pandas Index có tên

index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

3. Hiển thị Index

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

4. Chuyển Index thành DataFrame (giữ Index gốc)

print("\nIndex chuyển thành DataFrame...\n", index.to_frame())

Ví dụ hoàn chỉnh

import pandas as pd

# Tạo Pandas Index có tên
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

# Hiển thị Index
print("Pandas Index...\n", index)

# Số lượng phần tử
print("\nSố phần tử (size)...\n", index.size)

# Kiểu dữ liệu
print("\nKiểu dữ liệu (dtype)...\n", index.dtype)

# Chuyển Index thành DataFrame (mặc định index=True)
print("\nIndex chuyển thành DataFrame...\n", index.to_frame())

Kết quả đầu ra

Pandas Index...
Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Số phần tử (size)...
5
Kiểu dữ liệu (dtype)...
object
Index chuyển thành DataFrame...
            Products
Products
Electronics  Electronics
Accessories  Accessories
Decor        Decor
Books        Books
Toys         Toys

Giải thích: DataFrame kết quả có Index là giá trị Index gốc ('Electronics', 'Accessories'...), và một cột 'Products' cũng chứa cùng giá trị. Hữu ích khi cần chuyển Index thành cột nhưng vẫn giữ Index để join/merge.