Pandas · Add group context to rows
Google Search Analytics
Course overviewGoogle Search · Reshape and compare groups

Add group context to rows

Repeat a device statistic beside each search and rank timings within device groups.

Step 1 of 3 · Learn

Keep rows while adding a summary

.groupby(...).transform("mean") returns one value per input row, aligned to its original index. It repeats each group mean beside that group’s rows instead of reducing the table to one row per group. Use dropna=False to keep a missing-device group.

indexgroupvalue
0A10
1B50
2A30
indexgroupvaluegroup_mean
0A1020
1B5050
2A3020
Three input rows remain three rows; group A's mean appears twice.

Compare with the group average

Subtract the group mean from the original response time. A positive difference means slower than that device's average; a negative difference means faster. Means ignore missing timings. A row with a missing timing has a missing difference.

State the ranking rule

Group .rank(method="dense", ascending=False) puts the largest timing at rank 1 within each device. Equal timings share a rank and the next distinct timing gets the next integer. Missing timings keep a missing rank; the default rank method is average, not dense.

indexgroupvalue
0A30
1A30
2A10
3B20
indexgroupvaluerank
0A301
1A301
2A102
3B201
Ties share rank 1; the next distinct value is rank 2, with a fresh ranking for B.
▷ Your turn

Return search_id, device, response_ms, and device_mean_ms for every search in source row order. Repeat each device's mean recorded response_ms on its rows, including missing device keys as a group. Ignore missing timings when calculating means and do not round. Save the DataFrame as result.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.