Share of the group total with transform
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
Add a `share` column with each order's revenue as a fraction of its region's total revenue, and return the columns `order_id`, `region`, `revenue` and `share` for every order, in the original order and with the original labels.
What this exercise teaches
transform keeps the shape of the input, so each order gets its own region's total next to it and the division lines up row by row. A plain .sum() collapses to one row per region, and dividing by that aligns on the index labels, which are regions on one side and order positions on the other, so you get NaN everywhere.
A hint if you get stuck
groupby(...)[col].transform("sum") returns the group total repeated on every row of that group, aligned with the original index.
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
- Largest order per rep with idxmaxPro
- Pivot table with totalsPro
- Fill missing values with the group meanPro