Pivot & Pivot Table

Python · Reshaping & Workflow

Theory

Pivoting turns the values of one column into column headers, giving a wide cross-tab such as cities down the side and months across the top. df.pivot(index='city', columns='month', values='amount') only rearranges data: it needs each (city, month) pair to appear once and raises an error on duplicates. df.pivot_table(...) also aggregates, so duplicates are fine: aggfunc='sum' (default 'mean'), several functions as a list, fill_value=0 for empty cells and margins=True to add an 'All' row and column with grand totals.

pd.crosstab(df['city'], df['month']) is a shortcut that counts how often each pair occurs; add values= and aggfunc= to aggregate instead, and normalize='index' to get row percentages. The result's row labels are the index; call reset_index() to make them a column again. melt() reverses a pivot.

Why we use it

Wide tables are what people read in reports and Excel: one row per entity, one column per period or category. pivot_table produces them in one call, with totals, and without writing a CASE WHEN per column as SQL needs.

When to use it

Use pivot_table for summary cross-tabs (it handles duplicates and totals), pivot only when each pair is unique and you just want to reshape, and crosstab for frequency tables. Keep data long (tidy) for further groupby and joins; pivot at the end for display.

How it works

  1. Long data: city, month, amount
  2. Is each (city, month) pair unique? Yes: pivot() can reshape it. No: Use pivot_table with aggfunc.
  3. Turn month values into columns, one row per city
  4. Fill empty cells (fill_value=0) and add totals (margins=True)
  5. Wide cross-tab report

Syntax

df.pivot(index='r', columns='c', values='v')
df.pivot_table(index='r', columns='c', values='v', aggfunc='sum', fill_value=0, margins=True)
pd.crosstab(df['r'], df['c'], normalize='index')

Example

report = df.pivot_table(index='city', columns='month', values='amount',
                        aggfunc='sum', fill_value=0, margins=True)

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