Skip to content

Export

เมื่อวิเคราะห์เสร็จแล้ว ต้อง export ผลลัพธ์ให้คนอื่นใช้งานต่อ ขั้นตอนนี้มี trap หลายจุดที่ทำให้ข้อมูลเสีย — โดยเฉพาะ leading zeros และ encoding

.to_csv() — ส่งออกเป็น CSV

Section titled “.to_csv() — ส่งออกเป็น CSV”
import pandas as pd
df = pd.DataFrame({
"product_id": ["P001", "P002", "P003"],
"name": ["เสื้อยืด", "กางเกง", "รองเท้า"],
"price": [350.00, 590.00, 1200.00],
"zipcode": ["01234", "00567", "10100"]
})
# พื้นฐาน
df.to_csv("output.csv", index=False)
# กำหนด encoding สำหรับภาษาไทย
df.to_csv("output.csv", index=False, encoding="utf-8-sig")

ปัญหา Leading Zeros เมื่อเปิดใน Excel

Section titled “ปัญหา Leading Zeros เมื่อเปิดใน Excel”
# CSV ที่มี zipcode "01234" เมื่อเปิดใน Excel จะกลายเป็น 1234
# แก้ไขได้ 2 วิธี:
# วิธี 1: Export เป็น Excel แทน (dtype ถูกรักษา)
df.to_excel("output.xlsx", index=False)
# วิธี 2: เพิ่ม = นำหน้าใน CSV (บังคับ Excel อ่านเป็น text)
df_export = df.copy()
df_export["zipcode"] = '="' + df_export["zipcode"] + '"'
df_export.to_csv("output_safe.csv", index=False)

.to_excel() — ส่งออกเป็น Excel

Section titled “.to_excel() — ส่งออกเป็น Excel”
# ต้องติดตั้ง openpyxl ก่อน
# pip install openpyxl
df.to_excel("report.xlsx", index=False, sheet_name="Sales")
# หลาย sheet ในไฟล์เดียว
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="Sales", index=False)
summary.to_excel(writer, sheet_name="Summary", index=False)

รักษา Types เมื่ออ่านกลับ

Section titled “รักษา Types เมื่ออ่านกลับ”
# ปัญหา: save แล้วอ่านกลับ dtype อาจเปลี่ยน
df.to_csv("data.csv", index=False)
df2 = pd.read_csv("data.csv") # zipcode กลายเป็น int!
# แก้: กำหนด dtype ตอนอ่านกลับ
df2 = pd.read_csv("data.csv", dtype={"zipcode": str, "product_id": str})
# หรือใช้ Parquet (รักษา dtype 100%)
df.to_parquet("data.parquet")
df2 = pd.read_parquet("data.parquet")
print(df2.dtypes) # dtype ตรงกับต้นฉบับ!

Parquet — format สำหรับ Data Pipeline

Section titled “Parquet — format สำหรับ Data Pipeline”
# pip install pyarrow
df.to_parquet("data.parquet", index=False)
df = pd.read_parquet("data.parquet")
# ข้อดี:
# - รักษา dtype ทุก column
# - ไฟล์เล็กกว่า CSV 2-10 เท่า
# - อ่าน/เขียนเร็วกว่า CSV มาก
# - รองรับ column-based query