GroupBy
GroupBy
Section titled “GroupBy”.groupby() คือเครื่องมือที่ทรงพลังที่สุดใน pandas สำหรับการสรุปข้อมูลตามกลุ่ม
แนวคิดเดียวกับ GROUP BY ใน SQL หรือ Pivot Table ใน Excel
แนวคิด Split → Apply → Combine
Section titled “แนวคิด Split → Apply → Combine”import pandas as pd
df = pd.DataFrame({ "category": ["เสื้อผ้า", "รองเท้า", "เสื้อผ้า", "accessories", "รองเท้า", "เสื้อผ้า"], "product": ["เสื้อ", "ผ้าใบ", "กางเกง", "หมวก", "แตะ", "เสื้อกล้าม"], "price": [350, 1200, 590, 299, 450, 250], "qty": [10, 3, 5, 20, 8, 15]}).groupby() พื้นฐาน
Section titled “.groupby() พื้นฐาน”# สรุปยอดขายตามหมวดหมู่grouped = df.groupby("category")["price"].sum()print(grouped)# category# accessories 299# รองเท้า 1650# เสื้อผ้า 1190
# หลาย aggregate functionsstats = df.groupby("category")["price"].agg(["mean", "min", "max", "count"])print(stats).agg() — หลาย column, หลาย function
Section titled “.agg() — หลาย column, หลาย function”summary = df.groupby("category").agg({ "price": ["mean", "sum"], "qty": ["sum", "max"]})print(summary)Named Aggregation (แนะนำ)
Section titled “Named Aggregation (แนะนำ)”# syntax ที่อ่านง่ายกว่า — ตั้งชื่อ column ผลลัพธ์ได้เลยsummary = df.groupby("category").agg( avg_price=("price", "mean"), total_revenue=("price", "sum"), total_qty=("qty", "sum"), product_count=("product", "count")).reset_index()
print(summary)# category avg_price total_revenue total_qty product_count# 0 accessories 299.00 299 20 1# 1 รองเท้า 825.00 1650 11 2# 2 เสื้อผ้า 396.67 1190 30 3GroupBy หลาย column
Section titled “GroupBy หลาย column”# เพิ่ม regiondf["region"] = ["กรุงเทพ", "กรุงเทพ", "เชียงใหม่", "กรุงเทพ", "เชียงใหม่", "กรุงเทพ"]
by_cat_region = df.groupby(["category", "region"]).agg( total=("price", "sum"), count=("product", "count")).reset_index()Custom Aggregation
Section titled “Custom Aggregation”# ใช้ lambda หรือ custom functiondf.groupby("category")["price"].agg( lambda x: x.max() - x.min() # range)- สร้าง Pivot Table: Insert > Pivot table
- Rows = category, Values = SUM(price)
- หรือสูตร:
=SUMIF(A:A, "เสื้อผ้า", C:C)
SELECT category, AVG(price) AS avg_price, SUM(price) AS total_revenue, COUNT(*) AS product_countFROM productsGROUP BY category;// C ต้อง sort แล้ว loop เอง// ไม่มี groupby ดั้งเดิม — ค่อนข้างยุ่งยาก