Python practice: Reshaping Data: Pivot Tables & Melting
Chapter 27 · 8 questions · included in full access
Question 1 · easy
Pivot tables vs GroupBy
Solve it in your browserWhen should an analyst use
pd.pivot_table()instead of standard.groupby()?Question 2 · easy
Two-dimensional summary with pivot_table
Solve it in your browserLoad
"sales.csv". Create a pivot table summarizing totalRevenuewithindex="Region",columns="Category",values="Revenue",aggfunc="sum", andfill_value=0. Print the total revenue for"North"Sheets (int(pt.loc["North", "Sheets"])):Question 3 · medium
Add Grand Totals with margins=True
Solve it in your browserLoad
"sales.csv". Build a pivot table of totalRevenuewithindex="Region",columns="Category",aggfunc="sum",fill_value=0, andmargins=True. Print the overall grand total (int(pt.loc["All", "All"])):Question 4 · medium
Average units with custom aggfunc
Solve it in your browserLoad
"sales.csv". Build a pivot table withindex="Region",columns="Category",values="Units",aggfunc="mean", andfill_value=0. Print the average units for East Profiles (round(pt.loc["East", "Profiles"], 1)):Question 5 · easy
Handle missing cell combinations with fill_value
Solve it in your browserLoad
"sales.csv". Notice North has no Profiles sales. Pivot total Revenue by Region and Category withfill_value=0. Print the value ofpt.loc["North", "Profiles"]as an integer:Question 6 · easy
Wide vs long data formats
Solve it in your browserIn data analytics and tidy data architecture, why is long format (stacked key-value rows) preferred over wide format (separate column per month)?
Question 7 · medium
Unpivot wide forecast columns with pd.melt()
Solve it in your browserGiven wide DataFrame
df = pd.DataFrame({"Rep": ["Asha", "Ravi"], "Q1": [10000, 15000], "Q2": [12000, 18000], "Q3": [14000, 20000]}), melt into long format withid_vars=["Rep"],value_vars=["Q1", "Q2", "Q3"],var_name="Quarter",value_name="Sales". Print the sum of"Sales":Question 8 · hard
Multi-index pivot table by Region and Rep
Solve it in your browserLoad
"sales.csv". Create a pivot table withindex=["Region", "Rep"],columns="Category",values="Revenue",aggfunc="sum", andfill_value=0. Print the number of rows in the resulting pivot table (len(pt)):
These questions are part of full access.
The first chapters of every track are free. Full access is a one-time payment.
See pricing