Python practice: Window Calculations & Group Transforms
Chapter 26 · 8 questions · included in full access
Question 1 · easy
Transform vs aggregate
Solve it in your browserWhat is the key architectural difference between
.groupby().transform()and.groupby().agg()in pandas?Question 2 · easy
Broadcast group total with .transform()
Solve it in your browserLoad
"sales.csv". Create a new columnsales["Region_Total"] = sales.groupby("Region")["Revenue"].transform("sum"). Printint(sales["Region_Total"].iloc[0]):Question 3 · medium
Calculate percentage of category total
Solve it in your browserLoad
"sales.csv". Computecat_totals = sales.groupby("Category")["Revenue"].transform("sum"). Then calculatesales["Pct"] = (sales["Revenue"] / cat_totals) * 100. Printround(sales["Pct"].iloc[0], 2):Question 4 · medium
Cumulative running total within group
Solve it in your browserLoad
"sales.csv". Sort by["Region", "OrderID"]. Compute cumulative running revenue within each Region using.groupby("Region")["Revenue"].cumsum(). Assign tosales["Run_Rev"]and printint(sales[sales["Region"] == "East"]["Run_Rev"].iloc[-1]):Question 5 · medium
Rank orders within region
Solve it in your browserLoad
"sales.csv". Compute order rank within each Region based on"Revenue"descending using.groupby("Region")["Revenue"].rank(ascending=False). Assign tosales["Rank"]. Print the OrderID of the order whereRegion == "North"andRank == 1.0:Question 6 · medium
Dense ranking for tie-breaking
Solve it in your browserGiven
df = pd.DataFrame({"Dept": ["Sales", "Sales", "Sales", "IT", "IT"], "Score": [90, 90, 80, 95, 85]}), rank scores within Dept descending withmethod="dense":df["Rank"] = df.groupby("Dept")["Score"].rank(method="dense", ascending=False). Printlist(df["Rank"].astype(int)):Question 7 · hard
Calculate group z-scores for anomaly detection
Solve it in your browserLoad
"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)):Question 8 · hard
Flag regional outliers
Solve it in your browserLoad
"sales.csv". Compute mean and standard deviation ofRevenuebyRegionusing.transform(). Flag orders where(sales["Revenue"] - mean_r).abs() > 1.5 * std_rasis_outlier. Print the count of outlier orders (int(sales["is_outlier"].sum())):
These questions are part of full access.
The first chapters of every track are free. Full access is a one-time payment.
See pricing