0
0
Pandasdata~3 mins

Why melt() for unpivoting in Pandas? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could reshape messy tables in one line instead of hours of copying?

The Scenario

Imagine you have a table with sales data for different products across several months, all in separate columns. You want to analyze sales trends over time, but the data is wide and hard to compare.

The Problem

Manually copying and rearranging columns into rows is slow and boring. It's easy to make mistakes, like mixing up months or missing data. Plus, if the data updates, you have to redo everything.

The Solution

The melt() function quickly turns wide tables into long tables by stacking columns into rows. This makes data tidy and ready for analysis without manual copying or errors.

Before vs After
Before
new_data = []
for month in ['Jan', 'Feb', 'Mar']:
    for i, row in df.iterrows():
        new_data.append({'Product': row['Product'], 'Month': month, 'Sales': row[month]})
new_df = pd.DataFrame(new_data)
After
new_df = df.melt(id_vars=['Product'], var_name='Month', value_name='Sales')
What It Enables

It lets you quickly reshape data to explore trends, create charts, and build models with tidy, easy-to-use tables.

Real Life Example

A store manager can transform monthly sales columns into a single 'Month' column to easily plot sales over time and spot which months perform best.

Key Takeaways

Manual reshaping is slow and error-prone.

melt() automates turning columns into rows.

This makes data tidy and ready for analysis.