GroupBy

Python · GroupBy & SQL-Style Analytics

Theory

groupby() answers questions like 'total sales per city'. It follows split-apply-combine: split the rows into groups by the values of a key column, apply an aggregation to each group separately, then combine the results into a new Series or DataFrame indexed by the group keys, sorted by key. df.groupby('city')['amount'].sum() is SQL's SELECT city, SUM(amount) ... GROUP BY city.

Group by several columns with a list, groupby(['city', 'month']). Named aggregation gives clear output columns: df.groupby('city').agg(orders=('amount', 'count'), total=('amount', 'sum'), avg=('amount', 'mean')). agg(['sum', 'mean']) applies several functions to one column. size() counts rows per group including NaN, while count() counts non-missing values per column. Add .reset_index() or pass as_index=False to get the keys back as normal columns; rows whose key is NaN are left out unless dropna=False.

Why we use it

Most reporting is per category - sales by region, headcount by department, revenue by month. groupby() does this in a single readable line, just like GROUP BY in SQL.

When to use it

Use groupby whenever you need a summary per category. For a cross-tab with one key down the rows and another across the columns, pivot_table() is more convenient; to keep every row and add the group value next to it, use transform().

How it works

  1. df.groupby('city').agg(...)
  2. Split: collect the rows for each city value
  3. Apply: run each aggregation on each group
  4. Combine: one row per city, indexed by city
  5. Need city as a normal column? Yes: reset_index() or as_index=False. No: Keep city as the index.
  6. Summary table

Syntax

df.groupby('key')['col'].sum()
df.groupby(['k1', 'k2']).agg(new=('col', 'func'), ...)
df.groupby('key', as_index=False).agg(...)
df.groupby('key').size()

Example

print(df.groupby('city').agg(orders=('amount', 'count'), total=('amount', 'sum')))

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic