Python practice: Window Calculations & Group Transforms

Chapter 26 · 8 questions · included in full access

  1. Question 1 · easy

    Transform vs aggregate

    What is the key architectural difference between .groupby().transform() and .groupby().agg() in pandas?

    Solve it in your browser
  2. Question 2 · easy

    Broadcast group total with .transform()

    Load "sales.csv". Create a new column sales["Region_Total"] = sales.groupby("Region")["Revenue"].transform("sum"). Print int(sales["Region_Total"].iloc[0]):

    Solve it in your browser
  3. Question 3 · medium

    Calculate percentage of category total

    Load "sales.csv". Compute cat_totals = sales.groupby("Category")["Revenue"].transform("sum"). Then calculate sales["Pct"] = (sales["Revenue"] / cat_totals) * 100. Print round(sales["Pct"].iloc[0], 2):

    Solve it in your browser
  4. Question 4 · medium

    Cumulative running total within group

    Load "sales.csv". Sort by ["Region", "OrderID"]. Compute cumulative running revenue within each Region using .groupby("Region")["Revenue"].cumsum(). Assign to sales["Run_Rev"] and print int(sales[sales["Region"] == "East"]["Run_Rev"].iloc[-1]):

    Solve it in your browser
  5. Question 5 · medium

    Rank orders within region

    Load "sales.csv". Compute order rank within each Region based on "Revenue" descending using .groupby("Region")["Revenue"].rank(ascending=False). Assign to sales["Rank"]. Print the OrderID of the order where Region == "North" and Rank == 1.0:

    Solve it in your browser
  6. Question 6 · medium

    Dense ranking for tie-breaking

    Given df = pd.DataFrame({"Dept": ["Sales", "Sales", "Sales", "IT", "IT"], "Score": [90, 90, 80, 95, 85]}), rank scores within Dept descending with method="dense": df["Rank"] = df.groupby("Dept")["Score"].rank(method="dense", ascending=False). Print list(df["Rank"].astype(int)):

    Solve it in your browser
  7. Question 7 · hard

    Calculate group z-scores for anomaly detection

    Load "sales.csv". Calculate the z-score of Revenue within each Category: mean = sales.groupby("Category")["Revenue"].transform("mean"), std = sales.groupby("Category")["Revenue"].transform("std"), sales["z_score"] = (sales["Revenue"] - mean) / std. Print the maximum z-score rounded to 2 decimal places (round(sales["z_score"].max(), 2)):

    Solve it in your browser
  8. Question 8 · hard

    Flag regional outliers

    Load "sales.csv". Compute mean and standard deviation of Revenue by Region using .transform(). Flag orders where (sales["Revenue"] - mean_r).abs() > 1.5 * std_r as is_outlier. Print the count of outlier orders (int(sales["is_outlier"].sum())):

    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