Để trả về Index mới chứa các giá trị được chọn bởi các chỉ số (indices) vị trí, hãy sử dụng phương thức index.take().
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. Lấy Index mới từ chỉ số vị trí [1, 2]
print("\nIndex mới từ chỉ số vị trí...\n", index.take([1, 2]))
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)
# Lấy Index mới từ chỉ số vị trí 1, 2
print("\nIndex mới từ chỉ số vị trí...\n", index.take([1, 2]))
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 mới từ chỉ số vị trí...
Index(['Accessories', 'Decor'], dtype='object', name='Products')
Giải thích: take([1, 2]) lấy phần tử tại vị trí 1 ('Accessories') và 2 ('Decor'). Vị trí 0-based. Tên Index ('Products') được bảo toàn. Hữu ích cho fancy indexing, sampling, reorder. Hỗ trợ chỉ số âm: -1 lấy phần tử cuối.