Unpivot device columns into labeled country-device rows.
Step 1 of 3 · Learn
Move column labels into rows
.melt() keeps id_vars as identifiers and unfolds value_vars into rows. var_name names the column holding the former labels; value_name names the column holding the cells. Use .sort_values() for the required row order.
index
region
phone
web
0
A
2
1
1
B
3
0
↓
index
region
device
rows
0
A
phone
2
2
A
web
1
1
B
phone
3
3
B
web
0
Each wide row becomes one long row for each selected device column.
Choose which columns to unfold
Explicit value_vars prevents unrelated columns from becoming measurements. Melt preserves zero and missing values; it does not remove empty-looking cells or aggregate rows.
index
region
phone
web
0
A
2
NA
1
B
0
4
↓
index
region
device
rows
0
A
web
NA
1
B
web
4
Only web is unfolded, and its missing cell stays missing.
Filter only after defining the rows
For a complete country-device report, retain zero cells. If a task asks for observed pairs only, melt first and then keep counts greater than zero. The row index created by melt is not the country-device key.
▷ Your turn
Convert wide_counts to a long DataFrame with columns country, device, and searches. Include desktop, mobile, and tablet, retaining zero counts. Sort country then device ascending and save the DataFrame as result.
wide_counts is a country-sorted report with columns country, desktop, mobile, and tablet. It counts searches with both country and device present and uses 0 for absent pairs. Country is a regular column, not the index.