ในการทำซ้ำแต่ละองค์ประกอบในดัชนี (Index) ต่างกันตามจำนวนที่ระบุ ให้ใช้เมธอด index.repeat() และส่งรายการจำนวนครั้งที่ต้องการทำซ้ำแต่ละค่า
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนี
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship'], name='Transport')
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. ทำซ้ำแต่ละค่าต่างกัน
print("\nResult after repeating each index element in a different way...\n", index.repeat([2, 3, 5, 7]))
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้างดัชนี
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship'], name='Transport')
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# ทำซ้ำ: Car 2 ครั้ง, Bike 3 ครั้ง, Airplane 5 ครั้ง, Ship 7 ครั้ง
print("\nResult after repeating each index element in a different way...\n", index.repeat([2, 3, 5, 7]))
ผลลัพธ์
Pandas Index... Index(['Car', 'Bike', 'Airplane', 'Ship'], dtype='object', name='Transport')
Number of elements in the index... 4
The dtype object... object
Result after repeating each index element in a different way... Index(['Car', 'Car', 'Bike', 'Bike', 'Bike', 'Airplane', 'Airplane', 'Airplane', 'Airplane', 'Airplane', 'Ship', 'Ship', 'Ship', 'Ship', 'Ship', 'Ship', 'Ship'], dtype='object', name='Transport')
คำอธิบาย
repeat([2, 3, 5, 7]) ทำซ้ำค่าตำแหน่งที่ 0 ('Car') 2 ครั้ง ตำแหน่งที่ 1 ('Bike') 3 ครั้ง ตำแหน่งที่ 2 ('Airplane') 5 ครั้ง ตำแหน่งที่ 3 ('Ship') 7 ครั้ง รวม 17 ค่า