Pivot table with totals
A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.
The task
Build a table of total revenue with one row per region and one column per product. Add a row and a column of totals, both labeled "Total", and show 0 where a region sold none of a product.
What this exercise teaches
margins=True appends a row and a column holding the aggregate across all groups, computed with the same aggfunc, so with sum you get grand totals. The default label is "All"; margins_name renames it. fill_value fills the empty cells before the totals are computed, so the totals still add up.
A hint if you get stuck
pivot_table has margins and margins_name parameters.
Try it now, free, no account needed
The first 15 tasks on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro adds timed mode and the certificate.
Open this exerciseMore exercises in Aggregating
- Total by groupPro
- Group means as a flat tablePro
- Count rows per groupPro
- Named aggregationsPro
- Group by two keysPro
- Pivot table with a fill valuePro
- Counts with crosstabPro
- Shares with value_countsPro
- Several statistics at oncePro
- Share of the group total with transformPro
- Largest order per rep with idxmaxPro
- Fill missing values with the group meanPro