HomeCourseModule 09 › Pivot tables — pivot_table()

Pivot tables — pivot_table()

Module 09 · Pandas Crash Course8 min readBeginner

What you'll learn

  • Build a pivot with index/columns/values
  • Add multiple value columns and aggregations
  • Handle missing cells with fill_value

The basic pivot

df.pivot_table(index="region",
               columns="quarter",
               values="amount",
               aggfunc="sum")

Rows = region. Columns = quarter. Cells = total amount.

Multiple aggregations

df.pivot_table(index="region",
               columns="quarter",
               values="amount",
               aggfunc=["sum", "mean", "count"])

Multiple value columns

df.pivot_table(index="region",
               values=["amount", "quantity"],
               aggfunc={"amount": "sum", "quantity": "sum"})

Fill empty cells

df.pivot_table(index="region", columns="quarter",
               values="amount", aggfunc="sum", fill_value=0)

With margins (totals row + column)

df.pivot_table(index="region", columns="quarter",
               values="amount", aggfunc="sum",
               margins=True, margins_name="Total")

crosstab — quick frequency pivot

pd.crosstab(df["region"], df["status"])
pd.crosstab(df["region"], df["status"], normalize="index")   # row percentages

Key takeaways

  • pivot_table(index, columns, values, aggfunc) = Excel pivot.
  • fill_value=0 stops NaN holes.
  • margins=True adds totals.
  • pd.crosstab is the shortcut for frequency tables.

Sales by product × month

Build a pivot of total sales with products as rows and months as columns. Add a totals row and column.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.