Lab: Full EDA Project
Lab: Full EDA Project
Section titled “Lab: Full EDA Project”ในแล็บสุดท้ายนี้ คุณจะทำ EDA แบบเต็มรูปแบบกับข้อมูลร้านอาหาร ครอบคลุมทุกทักษะที่เรียนมาตั้งแต่ PY-1 ถึง PY-5
-
สร้างข้อมูลจำลอง
import pandas as pdimport numpy as npnp.random.seed(42)n = 100orders = 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)}) -
Inspect — ใช้
.info(),.shape,.describe(),.isna().sum()ตรวจสอบ -
Clean ข้อมูลทั้งหมด:
price→ แปลงเป็น numeric (N/A → NaN)payment→ normalize เป็น lowercasebranch→ strip whitespace- เพิ่ม column
total= price * qty - เพิ่ม column
monthจาก date
-
Explore — ตอบคำถาม:
- เมนูไหนขายดีที่สุด (จำนวน order)?
- สาขาไหนมียอดขายรวมสูงสุด?
- ยอดขายแต่ละเดือนเป็นอย่างไร?
- ลูกค้าคนไหนจ่ายเงินมากที่สุด?
- วิธีชำระเงินอะไรนิยมที่สุด?
-
Export — สร้าง summary แล้ว export เป็น CSV (utf-8-sig)
Show Solution
# Step 2: Inspectprint(orders.shape)orders.info()print(orders.describe())print(orders.isna().sum())print(orders.head(10))
# Step 3: Cleanorders["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 customerstop_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: Exportsummary = 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 สำเร็จ!")