Melt (Unpivot)

Python · Reshaping & Workflow

Theory

melt() is the reverse of a pivot: it turns columns into rows, changing a wide table into a long one. df.melt(id_vars=['city'], value_vars=['Jan', 'Feb', 'Mar'], var_name='month', value_name='amount') keeps city as an identifier and creates one row per (city, month), with the old column name in 'month' and the cell value in 'amount'. Leave out value_vars to melt every column that is not an id_var.

Wide data is common in spreadsheets and exports (one column per month, per year or per question in a survey), but most pandas operations - groupby, filtering, plotting with a hue, joining to a calendar - work best on long, tidy data where each row is one observation. Rows come out grouped by original column (all Jan rows, then all Feb rows); sort afterwards if you need city order. pd.wide_to_long() handles column names with a common prefix like sales_2023, sales_2024.

Why we use it

Spreadsheets store periods as columns, which makes 'total per month' or 'trend over time' awkward. Melting puts the period into a column so the usual groupby, filter and plot tools work.

When to use it

Melt right after loading wide spreadsheet-style data, or before plotting several columns as one series. Pivot back with pivot_table only for the final report. In SQL this is UNPIVOT (or a UNION ALL per column).

How it works

  1. Wide table: one column per month
  2. Choose id_vars to keep (city)
  3. For each other column, emit one row per id value
  4. Store the column name in var_name, the cell in value_name
  5. Long table: city, month, amount

Syntax

df.melt(id_vars=['id'], value_vars=['c1', 'c2'], var_name='variable', value_name='value')

Example

long = wide.melt(id_vars='city', var_name='month', value_name='amount')
print(long.groupby('month')['amount'].sum())

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic