ในการสร้าง DataFrame จากดัชนี (Index) แต่บังคับใช้ดัชนีใหม่ (ไม่ใช่ดัชนีเดิม) ให้ใช้เมธอด index.to_frame() พร้อมตั้งค่า index=False
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนี Pandas
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. แปลงเป็น DataFrame บังคับดัชนีใหม่
print("\nIndex to DataFrame...\n", index.to_frame(index=False))
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้างดัชนี Pandas
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# บังคับดัชนีใหม่และแปลงเป็น DataFrame
print("\nIndex to DataFrame...\n", index.to_frame(index=False))
ผลลัพธ์
Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Number of elements in the index... 5
The dtype object... object
Index to DataFrame... Products
0 Electronics
1 Accessories
2 Decor
3 Books
4 Toys
คำอธิบาย
เมื่อตั้งค่า index=False ดัชนีเดิม ('Products') จะกลายเป็นคอลัมน์ทั่วไป และ DataFrame จะได้ดัชนีใหม่เป็นตัวเลข 0,1,2,3,4 (RangeIndex)