Pandas · Return to a long table
Google Search Analytics
Course overviewGoogle Search · Reshape and compare groups

Return to a long table

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.

indexregionphoneweb
0A21
1B30
indexregiondevicerows
0Aphone2
2Aweb1
1Bphone3
3Bweb0
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.

indexregionphoneweb
0A2NA
1B04
indexregiondevicerows
0AwebNA
1Bweb4
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.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.