แนวคิด
groupby().sum() ใช้จัดกลุ่มข้อมูลตามคอลัมน์ที่กำหนด แล้วคำนวณผลรวมของคอลัมน์ตัวเลขในแต่ละกลุ่ม เหมาะสำหรับการสรุปข้อมูล (aggregation)
ตัวอย่างโค้ด
import pandas as pd
df = pd.DataFrame({
"Apple": [5, 2, 7, 0],
"Banana": [4, 7, 5, 1],
"Carrot": [9, 3, 5, 1]
})
print("Input DataFrame:\n", df)
# Group by คอลัมน์ Apple แล้ว sum คอลัมน์อื่นๆ
g_sum = df.groupby('Apple').sum()
print("\nGroup by Apple แล้ว sum:\n", g_sum)
ผลลัพธ์
Input DataFrame:
Apple Banana Carrot
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
Group by Apple แล้ว sum:
Banana Carrot
Apple
0 1 1
2 7 3
5 4 9
7 5 5
การประยุกต์ใช้เพิ่มเติม
# Group by หลายคอลัมน์
df.groupby(['col1', 'col2']).sum()
# ระบุคอลัมน์ที่จะ sum (exclude non-numeric)
df.groupby('category')['sales', 'quantity'].sum()
# ใช้ agg สำหรับหลายฟังก์ชันพร้อมกัน
df.groupby('category').agg(
total_sales=('sales', 'sum'),
avg_price=('price', 'mean'),
count=('id', 'count')
)
# reset_index() เพื่อทำให้กลายเป็นคอลัมน์ปกติ
df.groupby('category').sum().reset_index()
หมายเหตุ
groupbyจะทำให้คอลัมน์ที่ group by กลายเป็น index (ใช้as_index=Falseเพื่อป้องกัน)- คอลัมน์ที่ไม่ใช่ตัวเลขจะถูกตัดออกโดยอัตโนมัติ (เว้นแต่จะระบุ
numeric_only=False) - รองรับฟังก์ชันสรุปข้อมูลอื่นๆ:
mean(),min(),max(),std(),median()ฯลฯ