Skip to content

Type Conversion

ข้อมูลจากโลกจริงมักมาในรูปแบบ string เสมอ ไม่ว่าจะจาก CSV, API หรือ user input การแปลงชนิดข้อมูลให้ถูกต้องคือก้าวแรกของการวิเคราะห์ข้อมูล

ฟังก์ชันแปลงชนิดข้อมูล

Section titled “ฟังก์ชันแปลงชนิดข้อมูล”
# str → int
age_str = "25"
age = int(age_str)
print(age + 1) # 26
# str → float
price_str = "199.50"
price = float(price_str)
# int/float → str
year = 2024
year_str = str(year)
# str → bool (ระวัง!)
print(bool("")) # False (string ว่าง)
print(bool("False")) # True! (string ไม่ว่าง)
print(bool(0)) # False
print(bool(1)) # True
# ข้อมูลที่แปลงไม่ได้จะ raise ValueError
dirty = "25 ปี"
# int(dirty) # ValueError: invalid literal for int()
# ใช้ try/except จัดการ
def safe_int(value):
try:
return int(value)
except (ValueError, TypeError):
return None
print(safe_int("42")) # 42
print(safe_int("N/A")) # None
print(safe_int(None)) # None

ตัวอย่างจากงานจริง

Section titled “ตัวอย่างจากงานจริง”
# ข้อมูลจาก CSV มักเป็น string ทั้งหมด
raw_data = ["100", "200", "N/A", "350", ""]
# แปลงเป็นตัวเลข พร้อมจัดการค่าผิดปกติ
clean_data = []
for item in raw_data:
try:
clean_data.append(float(item))
except ValueError:
clean_data.append(None)
print(clean_data)
# [100.0, 200.0, None, 350.0, None]
# หรือใช้ comprehension + safe function
clean_data = [safe_int(x) for x in raw_data]

เปรียบเทียบ Implicit vs Explicit Conversion

Section titled “เปรียบเทียบ Implicit vs Explicit Conversion”
# Implicit — Python แปลงให้อัตโนมัติ
result = 10 + 3.5 # int + float → float (14.5)
# Explicit — เราสั่งแปลงเอง
total = int(10.9) # 10 (ตัดทศนิยมทิ้ง ไม่ปัดเศษ!)
rounded = round(10.9) # 11 (ปัดเศษ)