Reshaping and Combining Data
Tidy data principles, wide vs long formats, pivot and melt, concatenation and joins across sources.
Intermediate · about 5 hours · difficulty 3/5
Learn first: Data Cleaning and Quality Checks
The same data can be arranged many ways, and each tool prefers a particular shape. Knowing how to move between shapes quickly saves hours.
Tidy data
In a tidy dataset each variable is a column, each observation is a row, and each type of observational unit is a table. Most tools (pandas groupby, ggplot2, BI tools) work best on tidy, long data.
Wide vs long
- Wide: one column per month, per year, per question. Nice for humans, awkward for analysis.
- Long: columns like
country,year,value. Easy to filter, group and plot. - pandas:
meltgoes wide to long;pivot/pivot_tablego long to wide. In SQL, UNPIVOT or UNION ALL does the first and conditional aggregation the second. In Power Query, Unpivot Columns.
Combining sources
- Concatenate / append tables with the same columns (monthly files, regions).
- Join on keys; standardise key formats first and check match rates.
- Explode list-like columns into rows; flatten nested JSON with
pd.json_normalize. - Binning continuous variables (
pd.cut) and creating calendar features (week, month, weekday).
Pitfall: pivoting data with duplicate index/column pairs, which errors or silently aggregates. Always know whether each key combination is unique. Move on when you can take a wide World Bank indicators file, reshape it long, join it to a second source and plot a multi-country trend.
Key concepts
- Tidy data principles
- melt: wide to long
- pivot and pivot_table
- concat and append
- Joining with match-rate checks
- Nested JSON and explode
- Binning and feature derivation
Mini project
Download World Bank GDP and population indicators (wide format), reshape them long, join them on country and year, compute GDP per capita, and chart five countries over 30 years.
Check yourself
Why do plotting and groupby operations usually prefer long rather than wide data?
Free resources
- Tidy Data (Hadley Wickham, JSS) (Journal of Statistical Software)
- pandas: reshaping and pivot tables (pandas)