Type Conversion
Type Conversion
Section titled “Type Conversion”ข้อมูลจากโลกจริงมักมาในรูปแบบ string เสมอ ไม่ว่าจะจาก CSV, API หรือ user input การแปลงชนิดข้อมูลให้ถูกต้องคือก้าวแรกของการวิเคราะห์ข้อมูล
ฟังก์ชันแปลงชนิดข้อมูล
Section titled “ฟังก์ชันแปลงชนิดข้อมูล”# str → intage_str = "25"age = int(age_str)print(age + 1) # 26
# str → floatprice_str = "199.50"price = float(price_str)
# int/float → stryear = 2024year_str = str(year)
# str → bool (ระวัง!)print(bool("")) # False (string ว่าง)print(bool("False")) # True! (string ไม่ว่าง)print(bool(0)) # Falseprint(bool(1)) # Trueจัดการ ValueError
Section titled “จัดการ ValueError”# ข้อมูลที่แปลงไม่ได้จะ raise ValueErrordirty = "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")) # 42print(safe_int("N/A")) # Noneprint(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 functionclean_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 (ปัดเศษ)=VALUE("123")— แปลง text เป็นตัวเลข=TEXT(123, "000")— แปลงตัวเลขเป็น text พร้อม format=IFERROR(VALUE(A1), "")— จัดการ error คล้าย try/except
CAST('123' AS INT)CAST(price AS VARCHAR)-- หรือ PostgreSQL'123'::integer#include <stdlib.h>int num = atoi("123");double price = atof("199.50");// C ไม่มี built-in error handling แบบ try/except