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

Python Pandas - Tạo DataFrame từ Index nhưng ép buộc Index mới

Để tạo DataFrame từ Index gốc nhưng ép buộc sử dụng Index mới (thay thế Index gốc), hãy dùng phương thức index.to_frame() với tham số index=False.

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 với Index mới

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

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)

# Ép buộc Index mới và chuyển thành DataFrame
# Index gốc bị thay thế bằng RangeIndex mặc định
print("\nIndex chuyển thành DataFrame...\n", index.to_frame(index=False))

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
0  Electronics
1  Accessories
2  Decor
3  Books
4  Toys

Giải thích: Mặc định to_frame() dùng giá trị Index làm cả cột dữ liệu và Index của DataFrame. Với index=False, Index gốc trở thành cột dữ liệu, DataFrame nhận RangeIndex mặc định (0,1,2...).