Skip to content

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]
})
# สรุปยอดขายตามหมวดหมู่
grouped = df.groupby("category")["price"].sum()
print(grouped)
# category
# accessories 299
# รองเท้า 1650
# เสื้อผ้า 1190
# หลาย aggregate functions
stats = 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)
# 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 3
# เพิ่ม region
df["region"] = ["กรุงเทพ", "กรุงเทพ", "เชียงใหม่", "กรุงเทพ", "เชียงใหม่", "กรุงเทพ"]
by_cat_region = df.groupby(["category", "region"]).agg(
total=("price", "sum"),
count=("product", "count")
).reset_index()
# ใช้ lambda หรือ custom function
df.groupby("category")["price"].agg(
lambda x: x.max() - x.min() # range
)