ในการสร้าง Series จากดัชนี (Index) โดยคงดัชนีและชื่อเดิมไว้ ให้ใช้เมธอด index.to_series() ใน Pandas
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนี Pandas
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
3. แปลงเป็น Series
print("\nIndex to series...\n", index.to_series())
ตัวอย่างโค้ดสมบูรณ์
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)
# แปลงเป็น Series
print("\nIndex to series...\n", index.to_series())
ผลลัพธ์
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 series... Products
Electronics Electronics
Accessories Accessories
Decor Decor
Books Books
Toys Toys
Name: Products, dtype: object
คำอธิบาย
index.to_series() สร้าง Series ที่มี ดัชนีเหมือนดัชนีเดิม และ ค่าเท่ากับดัชนีเดิม (ค่าและดัชนีเหมือนกันทุกคู่) ชื่อของ Series จะเป็นชื่อของดัชนีเดิม