Pandas · Pivot a report
Google Search Analytics
Course overviewGoogle Search · Reshape and compare groups

Pivot a report

Move unique country-device pairs into a wide table without aggregating again.

Step 1 of 3 · Learn

Map pairs to cells

.pivot(index="region", columns="device", values="rows") moves region values into the row index and device values into column labels. Each pair must occur only once. Pivot does not aggregate duplicate pairs; it raises an error instead.

indexregiondevicerows
0Aphone2
1Aweb1
2Bphone3
regionphoneweb
A21
B3NA
Each unique region-device pair becomes one cell. An absent pair stays missing.

Set the axis order

.sort_index() sorts row labels. .reindex(columns=[...]) sets an explicit column order and adds missing columns filled with missing values. The country index is not a data column until you call .reset_index().

Decide what missing cells mean

For counts from a complete search log, an absent country-device pair means zero searches. .fillna(0) is appropriate for that report, but not automatically for missing averages. After resetting the index, .rename_axis(columns=None) removes the column-axis name, not its labels.

indexregiondevicerows
0Aphone2
1Aweb1
2Bphone3
indexregionphoneweb
0A21
1B30
For these complete event counts, an absent pair means zero; reset_index restores region as a column.
▷ Your turn

Pivot country_device_counts into a DataFrame indexed by country, with columns desktop, mobile, and tablet in that order. Sort the country index ascending, retain its name country, and keep the column-axis name device. Leave absent pairs or device columns missing. Save the DataFrame as result.

country_device_counts contains one row per observed country-device pair, with columns country, device, and searches. It counts all search rows with both grouping keys present. Missing-key rows are excluded from these reshape exercises.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.