ในการแปลงดัชนี (Index) เป็นรายการ (list) ของค่า ให้ใช้เมธอด index.to_list() ใน Pandas
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนี
index = pd.Index([50.4, 10.2, 70.5, 110.5, 90.8, 50.6])
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. แปลงเป็นรายการ
print("\nList of the index values...\n", index.to_list())
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้างดัชนี
index = pd.Index([50.4, 10.2, 70.5, 110.5, 90.8, 50.6])
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# แปลงเป็นรายการ
print("\nList of the index values...\n", index.to_list())
ผลลัพธ์
Pandas Index... Float64Index([50.4, 10.2, 70.5, 110.5, 90.8, 50.6], dtype='float64')
Number of elements in the index... 6
The dtype object... float64
List of the index values... [50.4, 10.2, 70.5, 110.5, 90.8, 50.6]
คำอธิบาย
index.to_list() คืนค่า Python list ธรรมดาที่มีค่าเท่ากับในดัชนี เหมาะสำหรับการนำไปใช้กับฟังก์ชันที่รับ list หรือการประมวลผลทั่วไป