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.
index
region
device
rows
0
A
phone
2
1
A
web
1
2
B
phone
3
↓
region
phone
web
A
2
1
B
3
NA
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.
index
region
device
rows
0
A
phone
2
1
A
web
1
2
B
phone
3
↓
index
region
phone
web
0
A
2
1
1
B
3
0
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.