Python practice: Reshaping Data: Pivot Tables & Melting

Chapter 27 · 8 questions · included in full access

  1. Question 1 · easy

    Pivot tables vs GroupBy

    When should an analyst use pd.pivot_table() instead of standard .groupby()?

    Solve it in your browser
  2. Question 2 · easy

    Two-dimensional summary with pivot_table

    Load "sales.csv". Create a pivot table summarizing total Revenue with index="Region", columns="Category", values="Revenue", aggfunc="sum", and fill_value=0. Print the total revenue for "North" Sheets (int(pt.loc["North", "Sheets"])):

    Solve it in your browser
  3. Question 3 · medium

    Add Grand Totals with margins=True

    Load "sales.csv". Build a pivot table of total Revenue with index="Region", columns="Category", aggfunc="sum", fill_value=0, and margins=True. Print the overall grand total (int(pt.loc["All", "All"])):

    Solve it in your browser
  4. Question 4 · medium

    Average units with custom aggfunc

    Load "sales.csv". Build a pivot table with index="Region", columns="Category", values="Units", aggfunc="mean", and fill_value=0. Print the average units for East Profiles (round(pt.loc["East", "Profiles"], 1)):

    Solve it in your browser
  5. Question 5 · easy

    Handle missing cell combinations with fill_value

    Load "sales.csv". Notice North has no Profiles sales. Pivot total Revenue by Region and Category with fill_value=0. Print the value of pt.loc["North", "Profiles"] as an integer:

    Solve it in your browser
  6. Question 6 · easy

    Wide vs long data formats

    In data analytics and tidy data architecture, why is long format (stacked key-value rows) preferred over wide format (separate column per month)?

    Solve it in your browser
  7. Question 7 · medium

    Unpivot wide forecast columns with pd.melt()

    Given wide DataFrame df = pd.DataFrame({"Rep": ["Asha", "Ravi"], "Q1": [10000, 15000], "Q2": [12000, 18000], "Q3": [14000, 20000]}), melt into long format with id_vars=["Rep"], value_vars=["Q1", "Q2", "Q3"], var_name="Quarter", value_name="Sales". Print the sum of "Sales":

    Solve it in your browser
  8. Question 8 · hard

    Multi-index pivot table by Region and Rep

    Load "sales.csv". Create a pivot table with index=["Region", "Rep"], columns="Category", values="Revenue", aggfunc="sum", and fill_value=0. Print the number of rows in the resulting pivot table (len(pt)):

    Solve it in your browser

These questions are part of full access.

The first chapters of every track are free. Full access is a one-time payment.

See pricing