Pivoting Data Wider (Cast)
You'll learn how to reshape long data into wide format by spreading key-value pairs across multiple columns.
In the previous lesson, you learned to make data longer (melt). Now you'll do the opposite: make data wider. This is sometimes called "casting" because you're casting values outward into new columns.
The Core Idea
Imagine you have a long dataset where each row represents one observation with columns like id, variable, and value. Pivoting wider spreads unique values from one column into multiple new columns, filling cells with corresponding values from another column.
Analogy: Think of long data as a vertical filing system where each card has (person, metric, value). Pivoting wider is like creating a spreadsheet where each person gets one row, and each metric becomes its own column heading.
When to Use It
You pivot wider when:
- You need one row per entity (person, date, location)
- Different observations are currently stacked vertically but should be separate columns
- You're preparing data for analysis tools that expect wide format (like some statistical models)
In Practice
In Pandas, you use pivot() or pivot_table():
# Long format
df_long = pd.DataFrame({
'id': [1, 1, 2, 2],
'metric': ['height', 'weight', 'height', 'weight'],
'value': [170, 65, 180, 75]
})
# Pivot wider
df_wide = df_long.pivot(index='id', columns='metric', values='value')
# Result: columns are now 'height' and 'weight', one row per id
In R, you use pivot_wider() from the tidyverse.
Key Takeaway: Pivoting wider transforms long data into wide format by spreading one column's unique values into multiple new columns, with another column providing the cell values—the inverse of melting.