Skip to content

Lab: Full EDA Project

ในแล็บสุดท้ายนี้ คุณจะทำ EDA แบบเต็มรูปแบบกับข้อมูลร้านอาหาร ครอบคลุมทุกทักษะที่เรียนมาตั้งแต่ PY-1 ถึง PY-5

  1. สร้างข้อมูลจำลอง

    import pandas as pd
    import numpy as np
    np.random.seed(42)
    n = 100
    orders = pd.DataFrame({
    "order_id": range(1, n + 1),
    "date": pd.date_range("2024-01-01", periods=n, freq="D"),
    "customer_id": [f"C{str(x).zfill(3)}" for x in np.random.randint(1, 21, n)],
    "menu": np.random.choice(["ข้าวผัด", "ผัดไทย", "ส้มตำ", "ต้มยำ", "แกงเขียวหวาน"], n),
    "price": np.random.choice(["80", "120", "65", "150", "N/A", "95"], n),
    "qty": np.random.randint(1, 5, n),
    "payment": np.random.choice(["cash", "CASH", "Credit", "credit", "โอน"], n),
    "branch": np.random.choice(["สยาม", "ลาดพร้าว", " อารีย์ ", "สยาม "], n)
    })
  2. Inspect — ใช้ .info(), .shape, .describe(), .isna().sum() ตรวจสอบ

  3. Clean ข้อมูลทั้งหมด:

    • price → แปลงเป็น numeric (N/A → NaN)
    • payment → normalize เป็น lowercase
    • branch → strip whitespace
    • เพิ่ม column total = price * qty
    • เพิ่ม column month จาก date
  4. Explore — ตอบคำถาม:

    • เมนูไหนขายดีที่สุด (จำนวน order)?
    • สาขาไหนมียอดขายรวมสูงสุด?
    • ยอดขายแต่ละเดือนเป็นอย่างไร?
    • ลูกค้าคนไหนจ่ายเงินมากที่สุด?
    • วิธีชำระเงินอะไรนิยมที่สุด?
  5. Export — สร้าง summary แล้ว export เป็น CSV (utf-8-sig)

Show Solution
# Step 2: Inspect
print(orders.shape)
orders.info()
print(orders.describe())
print(orders.isna().sum())
print(orders.head(10))
# Step 3: Clean
orders["price"] = pd.to_numeric(orders["price"], errors="coerce")
orders["payment"] = orders["payment"].str.lower().str.strip()
orders["branch"] = orders["branch"].str.strip()
orders["total"] = orders["price"] * orders["qty"]
orders["month"] = orders["date"].dt.month
# Step 4a: เมนูยอดนิยม
menu_rank = orders["menu"].value_counts()
print("=== เมนูยอดนิยม ===")
print(menu_rank)
# Step 4b: ยอดขายตามสาขา
branch_sales = orders.groupby("branch").agg(
total_revenue=("total", "sum"),
order_count=("order_id", "count")
).reset_index().sort_values("total_revenue", ascending=False)
print("\n=== ยอดขายตามสาขา ===")
print(branch_sales)
# Step 4c: ยอดขายรายเดือน
monthly = orders.groupby("month").agg(
revenue=("total", "sum"),
orders=("order_id", "count")
).reset_index()
print("\n=== ยอดขายรายเดือน ===")
print(monthly)
# Step 4d: Top customers
top_cust = orders.groupby("customer_id").agg(
total_spent=("total", "sum")
).reset_index().sort_values("total_spent", ascending=False).head(5)
print("\n=== Top 5 ลูกค้า ===")
print(top_cust)
# Step 4e: วิธีชำระเงิน
print("\n=== วิธีชำระเงิน ===")
print(orders["payment"].value_counts())
# Step 5: Export
summary = orders.groupby(["branch", "menu"]).agg(
total_revenue=("total", "sum"),
avg_price=("price", "mean"),
total_qty=("qty", "sum")
).reset_index()
summary.to_csv("restaurant_summary.csv", index=False, encoding="utf-8-sig")
print("\nExport สำเร็จ!")