สมมติว่าคุณมี DataFrame และต้องการแปลงชนิดข้อมูล (dtype) ของคอลัมน์เฉพาะ เช่น จาก float เป็น int
วิธีแก้ปัญหา
- สร้าง DataFrame ที่มีคอลัมน์ Result เป็น float
- ใช้
df['Result'].astype(int)แปลงเป็น int - ตรวจสอบ dtype ก่อนและหลังด้วย
df.dtypes
ตัวอย่างโค้ด
import pandas as pd
data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'],
'Age': [13, 12, 12, 13, 12],
'Maths': [98, 59, 66, 95, 70],
'Science': [75, 96, 55, 49, 78],
'English': [79, 45, 70, 60, 80],
'Result': [8.1, 6.2, 6.3, 7.2, 8.3]}
df = pd.DataFrame(data)
print("ก่อนแปลง dtype:")
print(df.dtypes)
# แปลงคอลัมน์ Result จาก float เป็น int
df['Result'] = df['Result'].astype(int)
print("\nหลังแปลง dtype:")
print(df.dtypes)
print("\nDataFrame หลังแปลง:")
print(df)
ผลลัพธ์
ก่อนแปลง dtype:
Name object
Age int64
Maths int64
Science int64
English int64
Result float64
dtype: object
หลังแปลง dtype:
Name object
Age int64
Maths int64
Science int64
English int64
Result int64
dtype: object
คำอธิบาย:
astype()ใช้แปลง dtype ของ Series หรือ DataFrame- การแปลง float -> int จะตัดทศนิยมทิ้ง (truncate) ไม่ได้ปัดเศษ
- ดtype อื่นที่ใช้บ่อย: 'float64', 'int32', 'str', 'bool', 'datetime64[ns]', 'category'
- ใช้
pd.to_numeric()สำหรับแปลงข้อความเป็นตัวเลขได้ปลอดภัยกว่า (มี errors='coerce')