Topic 02 / 8

Data Aggregation & Grouping

~12 min read  //  Data Science Series  //  Coding India

The Power of groupby()

One of the most powerful features of Pandas is groupby(). It allows you to group data based on categories and apply an aggregation function to each group.

import pandas as pd

# Assuming we have a sales DataFrame
# Calculate total revenue per product category
category_sales = df.groupby("category")["revenue"].sum()
print(category_sales)

Multiple Aggregations

You can apply multiple functions at once using agg():

# Calculate total revenue, average price, and count of sales per category
summary = df.groupby("category").agg({
    "revenue": "sum",
    "price": "mean",
    "order_id": "count"
})

Pivot Tables

Pandas also supports Excel-style pivot tables for multidimensional aggregation:

# Average revenue by category and region
pivot = pd.pivot_table(
    df, 
    values="revenue", 
    index="category", 
    columns="region", 
    aggfunc="mean"
)