Để lặp lại (repeat) mỗi phần tử trong Index theo số lần khác nhau (không đồng đều), hãy sử dụng phương thức index.repeat() với danh sách số lần lặp lại tương ứng từng phần tử.
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(['Car', 'Bike', 'Airplane', 'Ship'], name='Transport')
3. Hiển thị Index
print("Pandas Index...\n", index)
4. Lặp lại từng phần tử số lần khác nhau
print("\nKết quả lặp lại mỗi phần tử số lần khác nhau...\n", index.repeat([2, 3, 5, 7]))
Ví dụ hoàn chỉnh
import pandas as pd
# Tạo Pandas Index có tên
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship'], name='Transport')
# 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ặp lại: Car 2 lần, Bike 3 lần, Airplane 5 lần, Ship 7 lần
print("\nKết quả lặp lại mỗi phần tử số lần khác nhau...\n", index.repeat([2, 3, 5, 7]))
Kết quả đầu ra
Pandas Index...
Index(['Car', 'Bike', 'Airplane', 'Ship'], dtype='object', name='Transport')
Số phần tử (size)...
4
Kiểu dữ liệu (dtype)...
object
Kết quả lặp lại mỗi phần tử số lần khác nhau...
Index(['Car', 'Car', 'Bike', 'Bike', 'Bike', 'Airplane', 'Airplane', 'Airplane', 'Airplane', 'Airplane', 'Ship', 'Ship', 'Ship', 'Ship', 'Ship', 'Ship', 'Ship'], dtype='object', name='Transport')
Giải thích: Danh sách [2,3,5,7] tương ứng 4 phần tử. Car×2, Bike×3, Airplane×5, Ship×7 = 17 phần tử. Tên Index ('Transport') được bảo toàn. Cũng chấp nhận số nguyên đơn lẻ: repeat(3) lặp tất cả 3 lần. Tương đương np.repeat(index.values, repeats) nhưng trả về Index.