ในการสร้างดัชนี (Index) ใหม่โดยแปลงชนิดข้อมูล (dtype) ของค่า ให้ใช้เมธอด index.astype() ใน 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. แปลงชนิดข้อมูลเป็น int64
index.astype('int64')
ตัวอย่างโค้ดสมบูรณ์
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)
# แปลงชนิดข้อมูลเป็น int64
print("\nIndex object after converting type...\n", index.astype('int64'))
ผลลัพธ์
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
Index object after converting type... Int64Index([50, 10, 70, 110, 90, 50], dtype='int64')
คำอธิบาย
astype() สร้างดัชนีใหม่ที่มีชนิดข้อมูลตามที่ระบุ ค่าทศนิยมจะถูกตัดทิ้ง (truncate) ไม่ใช่ปัดเศษ 50.4 กลายเป็น 50, 10.2 กลายเป็น 10 เป็นต้น