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

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

Để tạo Series giữ nguyên cả Index và tên của Index gốc, hãy sử dụng phương thức index.to_series().

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. Chuyển Index thành Series

print("\nIndex chuyển thành Series...\n", index.to_series())

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 Series
print("\nIndex chuyển thành Series...\n", index.to_series())

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 Series...
Products
Electronics    Electronics
Accessories    Accessories
Decor          Decor
Books          Books
Toys           Toys
Name: Products, dtype: object

Giải thích: Series kết quả có Index là giá trị Index gốc, values cũng là giá trị Index gốc, và name='Products' được kế thừa. Tương đương pd.Series(index.values, index=index, name=index.name). Hữu ích cho value_counts, map, etc.