Course contentsShow
← Data Science
Lesson 1145 of 2,14529. Data Wrangling WorkflowsFree lesson

Pivoting Data Longer (Melt)

Transform wide data into long format using melt/pivot_longer to gather multiple columns into key-value pairs.

Pivoting Data Longer (Melt)

What you'll learn: How to transform wide-format data into long format by gathering multiple columns into key-value pairs.

The Core Idea

When data violates tidy principles by spreading observations across multiple columns, you need to reshape it longer. Think of it like folding a wide poster so it fits in a tall tube—you're taking information that's spread horizontally and stacking it vertically instead.

Imagine a temperature dataset where each month is its own column: Jan, Feb, Mar, etc. This is wide format. To make it tidy, you'd "melt" those month columns into just two: one called month (holding "Jan", "Feb", "Mar"...) and one called temperature (holding the actual values). Now each row represents one observation: a temperature reading for a specific month.

Why Melt?

Many datasets arrive with measurements spread across columns because that's how humans naturally organize spreadsheets. But for analysis, you want each variable in its own column and each observation in its own row. Melting transforms:

City    | Jan | Feb | Mar
--------|-----|-----|----
NYC     | 32  | 35  | 45
LA      | 65  | 67  | 70

Into:

City | Month | Temp
-----|-------|-----
NYC  | Jan   | 32
NYC  | Feb   | 35
NYC  | Mar   | 45
LA   | Jan   | 65
...

The function is called melt() in Pandas (or pivot_longer() in other tools). You specify which columns to keep as identifiers and which to gather into the new key-value pair columns.

Key Takeaway: Melting/pivoting longer converts wide data into tidy long format by gathering multiple columns into two: one for the variable name (key) and one for its value, making datasets easier to filter, group, and visualize.