GroupBy — Splitting Calculations by Category
groupby() is one of the most important features in Pandas. It splits your data by category, runs a calculation on each group, then combines the results back into an output table. You'll reach for it constantly — sales totals by product, customer counts by city, revenue summaries by month.
python
import pandas as pd
df = pd.DataFrame({
"Category": ["Drink", "Drink", "Food", "Food", "Drink"],
"Product": ["Tea", "Coffee", "Cake", "Noodle", "Tea"],
"Sales": [3600, 3600, 2500, 5000, 2400]
})
category_sales = df.groupby("Category")["Sales"].sum()
product_sales = df.groupby("Product")["Sales"].sum().sort_values(ascending=False)
print("Sales by category:")
print(category_sales)
print("
Sales by product:")
print(product_sales)df.groupby("Category")["Sales"].sum() groups matching categories together and sums up the Sales for each. sort_values(ascending=False) then sorts them from highest sales to lowest.
You should see
Sales by category: Category Drink 9600 Food 7500 Name: Sales, dtype: int64 Sales by product: Product Tea 6000 Noodle 5000 Coffee 3600 Cake 2500 Name: Sales, dtype: int64Info
To understand GroupBy, remember it as split → apply → combine: split the data, apply a function, then combine the results back into a table.