BBampaa

Lessons › Python

Python lesson

Pivot tables

One row per store, one column per month. Lagos made 270, 160 and 390. Abuja made 80, 170 and 120.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

pivot_table makes the same grid as an Excel pivot table:

df.pivot_table(index="Store", columns="Month", values="Revenue", aggfunc="sum")

Output:

1 2 3
Abuja 80 170 120
Lagos 270 160 390

Key points

index="Store"The rows: one per store.
columns="Month"Across the top: one column per month.
values="Revenue"The numbers that go in the grid.
aggfunc="sum"How to combine them: "sum", "mean" or "count".

Put together: df.pivot_table(index="Store", columns="Month", values="Revenue", aggfunc="sum").

Practice

Try each one in your head first, then open the answer.

1. Build a pivot table of total revenue, a row for each store and a column for each month.
df.pivot_table(index="Store", columns="Month", values="Revenue", aggfunc="sum")
2. Build a pivot table of the average sale, a row for each store and a column for each month.
df.pivot_table(index="Store", columns="Month", values="Revenue", aggfunc="mean")
3. Make a pivot table of total revenue, with a row for each store and a column for each month.
df.pivot_table(index="Store", columns="Month", values="Revenue", aggfunc="sum")
4. Make a pivot table that counts the sales, with a row for each store and a column for each month.
df.pivot_table(index="Store", columns="Month", values="Revenue", aggfunc="count")
5. Your manager wants a grid of the average sale size: a row for each month and a column for each store.
df.pivot_table(index="Month", columns="Store", values="Revenue", aggfunc="mean")

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed