Type Casting
Type Casting
Section titled “Type Casting”เมื่ออ่าน CSV เข้ามา pandas อาจ detect ชนิดข้อมูลผิด — ราคาเป็น string, ปีเป็น float การแปลงให้ถูกต้องคือขั้นตอนสำคัญก่อนวิเคราะห์
.astype() — แปลงตรงๆ
Section titled “.astype() — แปลงตรงๆ”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 → floatdf["price"] = df["price"].astype(float)
# float → intdf["qty"] = df["qty"].astype(int)
# int → booldf["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' — แปลงไม่ได้ให้เป็น NaNclean = 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)Int64 — Nullable Integer Type
Section titled “Int64 — Nullable Integer Type”# ปัญหา: int column ที่มี NaN จะถูกแปลงเป็น floats = 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(), "ค่าว่าง")- แปลง text → number:
=VALUE(A1) - แปลง number → text:
=TEXT(A1, "0.00") - จัดรูปแบบ: Format > Number > เลือก format
CAST(price AS NUMERIC)CAST(qty AS INTEGER)-- PostgreSQL safe castingCASE WHEN price ~ '^\d+$' THEN price::int ELSE NULL END#include <stdlib.h>int qty = atoi("42");double price = strtod("199.50", NULL);// error check: strtod sets errno