Skip to content

Type Casting

เมื่ออ่าน CSV เข้ามา pandas อาจ detect ชนิดข้อมูลผิด — ราคาเป็น string, ปีเป็น float การแปลงให้ถูกต้องคือขั้นตอนสำคัญก่อนวิเคราะห์

import pandas as pd
df = pd.DataFrame({
"price": ["100", "250", "75", "430"],
"qty": [1.0, 2.0, 3.0, 4.0],
"is_sale": [1, 0, 1, 0]
})
# str → float
df["price"] = df["price"].astype(float)
# float → int
df["qty"] = df["qty"].astype(int)
# int → bool
df["is_sale"] = df["is_sale"].astype(bool)
print(df.dtypes)

pd.to_numeric() — แปลงอย่างปลอดภัย

Section titled “pd.to_numeric() — แปลงอย่างปลอดภัย”
dirty = pd.Series(["100", "250", "N/A", "430", ""])
# errors='coerce' — แปลงไม่ได้ให้เป็น NaN
clean = pd.to_numeric(dirty, errors="coerce")
print(clean)
# 0 100.0
# 1 250.0
# 2 NaN
# 3 430.0
# 4 NaN
# errors='ignore' — แปลงไม่ได้ให้คงค่าเดิม (ไม่แนะนำ)
# errors='raise' — แปลงไม่ได้ให้ error (default)
# ปัญหา: int column ที่มี NaN จะถูกแปลงเป็น float
s = pd.Series([1, 2, None, 4])
print(s.dtype) # float64 (ไม่ใช่ int!)
# แก้ด้วย Int64 (ตัว I ใหญ่!)
s = pd.Series([1, 2, None, 4], dtype="Int64")
print(s)
# 0 1
# 1 2
# 2 <NA>
# 3 4
# dtype: Int64
# แปลง column ที่มีอยู่
df["qty"] = df["qty"].astype("Int64")

ตรวจสอบ dtype หลัง casting

Section titled “ตรวจสอบ dtype หลัง casting”
# ตรวจสอบว่า dtype ถูกต้อง
print(df.dtypes)
print(df.info())
# ตรวจสอบค่าที่แปลงไม่ได้ (กลายเป็น NaN)
converted = pd.to_numeric(dirty, errors="coerce")
failed = dirty[converted.isna() & dirty.notna()]
print(f"แปลงไม่ได้ {len(failed)} ค่า: {failed.tolist()}")

Best Practice: ลำดับการ clean

Section titled “Best Practice: ลำดับการ clean”
# 1. strip whitespace ก่อน
df["price"] = df["price"].str.strip()
# 2. replace ค่าผิดปกติ
df["price"] = df["price"].replace(["N/A", "-", ""], pd.NA)
# 3. แปลงชนิดข้อมูล
df["price"] = pd.to_numeric(df["price"], errors="coerce")
# 4. ตรวจสอบ
print(df["price"].isna().sum(), "ค่าว่าง")