Pandas · Aggregate while pivoting
Google Search Analytics
Course overviewGoogle Search · Reshape and compare groups

Aggregate while pivoting

Build wide counts, totals, and means directly from search events.

Step 1 of 3 · Learn

Aggregate repeated pairs

.pivot_table() can combine repeated index-column pairs. Always choose aggfunc explicitly: "size" counts rows, "sum" adds values, and "mean" averages recorded values. Its default is mean, not count.

indexregiondeviceevent
0Aphone1
1Aphone2
2Aweb3
3Bphone4
regionphoneweb
A21
B10
Two A-phone events are counted into one cell.

Choose counts or measurements

fill_value=0 fills empty result cells after aggregation. It suits event counts and totals when no events means zero. Leave absent mean cells missing; a missing average is not a measured value of zero.

indexregiondevicevalue
0Aphone10
1Aphone30
2Bweb20
regionphoneweb
A20NA
BNA20
Mean summarizes the measurements; a missing measurement group is not a zero.

Keep the output contract explicit

For these tasks, first drop rows missing country or device. Order device columns with .reindex(columns=[...]) and sort the country index. With count and total reports, fill_value=0 in reindex also supplies a device column absent from the entire input. Do not use that fill for mean reports. For means, dropna=False keeps all-missing result rows and columns after those input rows with missing keys have been excluded.

▷ Your turn

From searches, exclude rows missing country or device and count search rows for each country-device pair. Return a country-indexed DataFrame sorted by country, with desktop, mobile, and tablet columns in that order. Fill absent pairs and device columns with 0. Preserve axis names country and device. Save the DataFrame as result.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.