Data Science · Level 3 Aggregation

pandas Pivot Tables

Turn a long sales list into a region-by-quarter grid with pivot_table(), using totals and zeros for empty cells.

  • pivot_table(index, columns, values)
  • aggfunc="sum"
  • fill_value=0 for empty cells

pivot_table reshapes a long table into a grid: one row per index value, one column per columns value. Trap: the default aggfunc is the mean, not the sum.

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

Write sales_grid(df) that returns a pivot table of total amount with one row per region, one column per quarter and 0 where there were no sales, for example North's two Q1 sales of 100 and 50 give 150.

solution.py
Test Suites Pending
Output